Jquery动态图像调整大小不正确的图像尺寸

时间:2010-02-17 16:03:51

标签: jquery html css

出于某种原因,在点击我正在创建的图库时,在.product-image容器中加载新图像时,分配给CSS的尺寸并不总是如此。我认为这是由于在图像仍在加载时分配css属性引起的,因为它似乎只发生在较大的图像上。再次单击“.more-views a”后,将计算正确的维数。

function loadNewImage(newurl) {

        jQuery(".col-main .product-image a").attr("href",newurl);
        jQuery(".col-main .product-image img").attr("src", newurl);
        jQuery(".col-main .product-image img").css({'width': '','height':''});

    }

    function resizeImageByAspect(ele) {
        var maxWidth = 465;
        var maxHeight = 436;
        var ratio = 0;
        var width = ele.width(); 
        var height = ele.height();
        ele.css("width", width);
        ele.css("height", height);

        if (width > maxWidth) {
            ratio = maxWidth / width;
            ele.css("width", maxWidth);
            ele.css("height", height * ratio);
            height = height * ratio;
            width = width * ratio;
        }

        if (height > maxHeight) {
            ratio = maxHeight / height;
            ele.css("height", maxHeight);
            ele.css("width", width * ratio);
            width = width * ratio;
        }
    }
    jQuery(document).ready(function(){
        resizeImageByAspect(jQuery(".col-main .product-image img"));

        jQuery(".more-views a").click(function(event){
            jQuery(".col-main .product-image img").fadeOut("fast", function(){


                loadNewImage(jQuery(event.target).parent().attr('href'));

                resizeImageByAspect(jQuery(".col-main .product-image img"));
            }).delay(500);

            jQuery(".col-main .product-image img").fadeIn("fast");
            return false;
        });


    });

2 个答案:

答案 0 :(得分:2)

我建议在设置新的src属性之前在图像上添加一个加载处理程序。让此加载处理程序运行您的调整大小代码。

function loadNewImage(newurl) { 

    jQuery(".col-main .product-image a").attr("href",newurl); 
    jQuery(".col-main .product-image img").unbind('load').load( function() {
         resizeImageByAspect($(this));
    }).attr("src", newurl); 
    jQuery(".col-main .product-image img").css({'width': '','height':''}); 

} 

答案 1 :(得分:0)

请参阅旧版stackoverflow问题:Browser-independent way to detect when image has been loaded

浏览这些评论,然后决定是否要在调整大小之前尝试使用事件处理程序来监视已完成的图像加载。