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.
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('img');
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('img'); // img.setAttribute("width", "300"); img.style.width = "300px"; } </script> </body> </html>
Rendering:
[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!