In the work of the company, we often want to present product pages to customers. Due to the different formats and sizes of the images uploaded by the customer, scaling may cause deformation, so we took some time on Sunday, I wrote a piece of JS Code that supports perfect image scaling.
First, add a <div> </div> label to the image. The height or width cannot be defined in img, as shown below:
<Div class = "product_img_div"> </div> write code in CSS :. product_img_div {width: 210px; height: pixel PX; overflow: hidden}
The function is to hide the overflow part during image loading, so that the interface will not be too ugly.
Copy codeThe Code is as follows:
ReSizeImg ("product_img", 200,180 );
Function ReSizeImg (cName, w, h ){
Var reImgs = document. getElementsByTagName ("img ");
For (j = 0; j <reImgs. length; j ++ ){
If (reImgs [j]. className = cName & (reImgs [j]. height> h | reImgs [j]. width> w )){
If (reImgs [j]. height = reImgs [j]. width ){
ReImgs [j]. height = h; reImgs [j]. width = w;
} Else if (reImgs [j]. height> reImgs [j]. width ){
ReImgs [j]. height = h;
} Else if (reImgs [j]. height <reImgs [j]. width ){
ReImgs [j]. width = w;
}
}
}
}
After the test, the image size is scaled perfectly, which also solves the problem that the interface will be ugly during loading.