开发者

Jquery dynamic image resizing not taking correct image dimentions

For some reason while clicking around this gallery i'm creating, the dimensions that get assigned to the CSS don't always take when a new image gets loaded in the .product-image container. I think it's caused by assigning css attributes while an image is still loading, as it only seems to happen with larger images. Once ".more-views a" is clicked again, the correct dimentions are calculated.

function loadNewImage(newurl) {

        jQuery(".col-main .product-im开发者_如何学Cage 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;
        });


    });


I'd suggest adding a load handler on the image before setting the new src attribute. Have this load handler run your resize code.

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':''}); 

} 


See this older stackoverflow question: Browser-independent way to detect when image has been loaded

Wade through those comments, and then decide if you want to try and use an event handler to watch for the completed loading of your images before you do the size adjustment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜