jQuery动态改变图片显示大小(修改版)

$(document).ready(function() {  
     $('.post img').each(function() {  
     var maxWidth = 100; // 图片最大宽度  
     var maxHeight = 100;    // 图片最大高度  
     var ratio = 0;  // 缩放比例  
     var width = $(this).width();    // 图片实际宽度  
     var height = $(this).height();  // 图片实际高度  
    
     // 检查图片是否超宽  
     if(width > maxWidth){  
         ratio = maxWidth / width;   // 计算缩放比例  
         $(this).css("width", maxWidth); // 设定实际显示宽度  
         height = height * ratio;    // 计算等比例缩放后的高度   
         $(this).css("height", height);  // 设定等比例缩放后的高度  
     }  
    
     // 检查图片是否超高  
     if(height > maxHeight){  
         ratio = maxHeight / height; // 计算缩放比例  
         $(this).css("height", maxHeight);   // 设定实际显示高度  
         width = width * ratio;    // 计算等比例缩放后的高度  
         $(this).css("width", width * ratio);    // 设定等比例缩放后的高度  
     }  
 });  
 });  
故修改代码如下:

jQuery(window).load(function () {  
            jQuery("div.product_info img").each(function () {  
                DrawImage(this, 680, 1000);  
            });  
        });  
        function DrawImage(ImgD, FitWidth, FitHeight) {  
            var image = new Image();  
            image.src = ImgD.src;  
            if (image.width > 0 && image.height > 0) {  
                if (image.width / image.height >= FitWidth / FitHeight) {  
                    if (image.width > FitWidth) {  
                        ImgD.width = FitWidth;  
                        ImgD.height = (image.height * FitWidth) / image.width;  
                    } else {  
                        ImgD.width = image.width;  
                        ImgD.height = image.height;  
                    }  
                } else {  
                    if (image.height > FitHeight) {  
                        ImgD.height = FitHeight;  
                        ImgD.width = (image.width * FitHeight) / image.height;  
                    } else {  
                        ImgD.width = image.width;  
                        ImgD.height = image.height;  
                    }  
                }  
            }  
        }  
原文地址:https://www.cnblogs.com/Mr0909/p/4119017.html