SoFunction
Updated on 2025-02-28

Example of JS reducing image size in equal proportion

In order to improve the user experience, when website users upload pictures, we cannot let users process the pictures themselves to meet our requirements.

Usually, for pages like the physical display of products on Taobao, what we need to control is mainly the width of the picture.

Considering some problems that may be caused by the order of html page parsing, I decided to implement it by defining a simple functional function and then adding an onload event to the img element to call it. The code is as follows:

JS part

Copy the codeThe code is as follows:

<script type="text/javascript">
 function changeImg(objImg)
 {
var most = 690;         //Set the maximum width
     if( > most)
     {
         var scaling = 1-(-most)/;   
//Calculate the reduction ratio
         = *scaling;
= ;

// = *scaling;    // When setting the height of the img element, equal-scale reduction is required
     }

 }
 </script>


HTML Call Part

Copy the codeThe code is as follows:

 <img src="" onload="changeImg(this);" />