Jquery偶尔会在图像上返回零高度和宽度

Tan*_*oro 12 javascript jquery

我观察到一种不寻常的行为.我有一个浮动的对话框,我在其中放置一个图像.我想使用jquery获取图像大小,并将其div容器调整为适当的大小.它运行得相当好,但该功能偶尔会返回零作为图像大小.

$('#dialogueContainer').html('<div class="dialogue"><img src="/photos/' + file + '" id="lightImage" /></div>');

var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();

console.log(imageHeight + 'x' + imageWidth); //<-- This occasionally returns "0x0"
Run Code Online (Sandbox Code Playgroud)

我怀疑当jquery试图测量它的高度和宽度时,图像可能没有在DOM中准备好.有什么想法吗?

Jas*_*per 5

load在将元素添加到DOM之前,可以将事件处理程序绑定到元素,以便在可用时获取宽度/高度.您还可以使用CSS或内联属性明确设置图像的宽度/高度.

//create an img element, passing attribute values as we do, then bind an event handler to the `load` event for the image
var $img = $('<img />', { src : '/photos/' + file, id : 'lightImage' }).on('load', function () {

    //now that the image has loaded we can be sure the height/width values we receive are accurate
    var imageHeight = $(this).height(),
        imageWidth  = $(this).width();

    console.log(imageHeight + 'x' + imageWidth);
});

//now change the HTML of the container, emptying the container, then appending a div element with the `dialogue` class which also has a child img element (our image from above)
$('#dialogueContainer').html($('<div />', { class : 'dialogue' }).html($img));
Run Code Online (Sandbox Code Playgroud)

我喜欢在将load事件处理程序添加到DOM或更改它的源之前将事件处理程序绑定到元素,这样您就知道load事件在图像实际加载时就已存在(这可以从缓存中快速发生).

请注意,这.on()是jQuery 1.7中的新增内容,在这种情况下替换.bind()(早期版本).

更新

我想强调的是,如果您知道图像的尺寸,则应明确声明它们(这是更快的浏览器渲染的最佳实践):

<img width="100px" height="200px" src="..." />
Run Code Online (Sandbox Code Playgroud)


Mik*_*ier 5

你没错,图片没有加载.

最糟糕的是,在IE中,有时报告的大小类似于40x60(图像未加载时看到的小图标).

jQuery报告load事件可以与图像一起使用:http: //api.jquery.com/load-event/

我很久以前试过解决这个问题,跨浏览器,我最终轮询图像大小以触发自定义"加载"事件.

谢谢