Home > Web Front-end > Front-end Q&A > How to change image width with javascript

How to change image width with javascript

青灯夜游
Release: 2021-10-08 17:37:36
Original
2608 people have browsed it

Method: 1. Use the "document.getElementById('id value')" statement to obtain the picture object; 2. Use "picture object.setAttribute("width", "width value")" or "picture object The .style.width="value" statement changes the image width.

How to change image width with javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript method to change the width of the image

<img  id="img" src="img/2.jpg"    style="max-width:90%"  style="max-width:90%"/ alt="How to change image width with javascript" >
Copy after login

1. Get the image object based on the id value

var img=document.getElementById(&#39;img&#39;);
Copy after login

2. Use setAttribute("width", "value") or the width attribute of the style object to change the image width

img.setAttribute("width", "宽度值");
// 或
img.style.width = "宽度值";
Copy after login

Complete implementation code:

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<img  id="img" src="img/2.jpg"    style="max-width:90%"  style="max-width:90%" / alt="How to change image width with javascript" ><br /><br />
		<button onclick="myFunction()">改变图片宽度</button>
		<script type="text/javascript">
			function myFunction() {
				var img = document.getElementById(&#39;img&#39;);
				// img.setAttribute("width", "300");
				img.style.width = "300px";
			}
		</script>
	</body>
</html>
Copy after login

Rendering:

How to change image width with javascript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to change image width with javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template