Home >Web Front-end >JS Tutorial >How to reduce image size in JavaScript

How to reduce image size in JavaScript

青灯夜游
青灯夜游Original
2021-09-09 17:38:403702browse

JS method to reduce the image: 1. Use the setAttribute() method, the syntax is "image object.setAttribute("width", "smaller width value")". 2. Use the width attribute of the style object, with the syntax "picture object.style.width="smaller value"".

How to reduce image size in JavaScript

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

Methods to reduce image size in JavaScript

Method 1: Use setAttribute()

<img  id="img" src="img/1.jpg"    style="max-width:90%" / alt="How to reduce image size in JavaScript" ><br /><br />
<button onclick="myFunction()">缩小图片</button>
<script type="text/javascript">
	function myFunction() {
		document.getElementById(&#39;img&#39;).setAttribute("width", "300");
	}
</script>

Output result:

How to reduce image size in JavaScript

Method 2: Use the width attribute of the style object

<img  id="img" src="img/2.jpg"    style="max-width:90%" / alt="How to reduce image size in JavaScript" ><br /><br />
<button onclick="myFunction()">缩小图片</button>
<script type="text/javascript">
	function myFunction() {
		document.getElementById(&#39;img&#39;).style.width="300px";
	}
</script>

Output result:

How to reduce image size in JavaScript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to reduce image size in 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