Javascript image zoom in out proportionally, width and height will not exceed the specified value

Lionsure 2020-06-29 Original by the website

Web pages have size restrictions. The image displayed on the web page cannot exceed its size; if the image exceeds its size, it must be scaled down to ensure that it is not deformed. To achieve it, you can use either Css or javascript. If the webpage is compatible with old browsers(such as IE6), usually use javascript, because IE6 does not support max-width and max-height, use expression() and consume too much resources; use javaScript to write a function to call directly, which is convenient and efficient.

 

The Method of javascript image zoom in out proportionally, width and height will not exceed the specified value:

w maximum width, h maximum height
       function ZoomImage(obj,w,h)
       {
              var objCon = document.getElementById(obj);
              var ImgCell = objCon.getElementsByTagName("img");
              for(var i=0;i < ImgCell.length;i++)
              {
                     var ImgWidth = ImgCell(i).width;
                     var ImgHeight = ImgCell(i).height;
                     if(ImgWidth > w)
                     {
                            var newHeight = w*ImgHeight/ImgWidth;
                            if(newHeight <= h)
                            {
                                   ImgCell(i).width = w;
                                   ImgCell(i).height = newHeight;
                            }
                            else
                            {
                                   ImgCell(i).height = h;
                                   ImgCell(i).width = h*ImgWidth/ImgHeight;
                            }
                     }
                     else
                     {
                            if(ImgHeight > h)
                            {
                                   ImgCell(i).height = h;
                                   ImgCell(i).width = h*ImgWidth/ImgHeight;
                            }
                            else
                            {
                                   ImgCell(i).width = ImgWidth;
                                   ImgCell(i).height = ImgHeight;
                            }
                     }
              }
       }

Call:

ZoomImage(parentNode,width,height)

parentNode represents the parent object ID of image;

width represents the width of image;

height represents the height of image.