繁体   English   中英

javascript:如何在加载后设置图像的宽度?

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

所以,我正在使用facebox来整洁地显示图像,我写了一个函数来帮助处理真正大图像的大小:(小提琴: 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 adjust 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);
    });
}

但问题是图像保持完整大小,永远不会变为500(我用于img_width的当前值)。

如何在加载后更改图像的宽度,但是足够快,没有人注意到?

我已在Chrome和Safari中使用此html进行了测试:

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

尝试这个

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

干得好:

更换:

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

有:

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

这个新代码监听reveal事件,并在所有元素到位后相应地设置宽度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM