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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值