开发者

javascript: how do I set the width of an image after it loads?

开发者 https://www.devze.com 2023-03-25 18:30 出处:网络
So, I\'m using facebox to display images neatly, and I wrote a function to help with handeling the size of really big images: (fiddle: http://jsfiddle.net/LPF85/)

So, I'm using facebox to display images neatly, and I wrote a function to help with handeling the size of really big images: (fiddle: http://jsfiddle.net/LPF85/)

function open_img_in_face_box(id, width){
    max_width = $j(document).width();
    max_height = $j(document).height();
    padding = 50;

    max_width = max_width - (2 * padding);
    max_height = max_height - (2 * padding);

    passed_width = width || max_width;

    var img = $j('#' + id); 
    dom_img = document.getElementById(id); 

    // display 
    jQuery.facebox({ image: img.attr('src') });

    // center and adju开发者_运维百科st size
    var aspect_ratio = img.width() / img.height();
    var img_width = passed_width;
    var img_height = passed_width / aspect_ratio;

    window_center_y = max_height / 2;
    window_center_x = max_width / 2;

    offset_y = window_center_y - (img_height / 2);
    offset_x = window_center_x - (img_width / 2);

    var fbx = $j('#facebox');
    fbx.css('left', offset_x + 'px !important');
    fbx.css('top', offset_y + 'px !important')

    $j("#facebox .image img").load(function(){
        $j(this).width(img_width);
    });
}

but the problem is that the image remains full size, and never gets changed to 500 (the current value I'm using for img_width).

How do I change the width of the image after it loads, but quickly enough so no one notices?

I've tested this in Chrome, and Safari with this html:

<img id="facebox_img" onclick="open_img_in_face_box('facebox_img', 500)" src="/medias/50/original.jpg" width="300" />


Here you go:

Replace:

$j("#facebox .image img").load(function(){
    $j(this).width(img_width);
});

with:

 $j(document).bind('reveal.facebox', function() { 
    $j("#facebox .image img").width(width);
 }) 

This new code listens to the reveal event and sets the width accordingly once all the elements are in place.


Try this

$j("#facebox .image img").each(function(){
    $(this).load(function(){
        $j(this).width(img_width);
    }).attr("src", $j(this).attr("src"));
});
0

精彩评论

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