Home  >  Article  >  Web Front-end  >  How to change image width with javascript

How to change image width with javascript

青灯夜游
青灯夜游Original
2021-10-08 17:37:362574browse

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" >

1. Get the image object based on the id value

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

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

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

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>

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!

Statement:
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