Jquery偶尔会在图像上返回零高度和宽度 [英] Jquery occasionally returns zero height and width on image

查看:78
本文介绍了Jquery偶尔会在图像上返回零高度和宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am observing an unusual behavior. I have a floating dialogue box in which I am placing an image. I want to get the image size using jquery and resize its div container to the appropriate size. It works fairly well, but the function occasionally returns zeros as the image sizes.

$('#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"

我怀疑图片可能还没准备好在jquery尝试测量其高度和宽度时在DOM中。有什么想法?

I suspect that the image may not be ready in the DOM when jquery attempts to measure its height and width. Any thoughts?

推荐答案

你是对的,没有加载图像。

You're right, the image is not loaded.

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

Worst, in IE, sometimes the size reported is something like 40x60 (the small icon you see when the image is not loaded yet).

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

jQuery reports that the load event can be used with images: http://api.jquery.com/load-event/

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

I tried a long time ago to solve this problem, cross browser, and I ended up polling the image sizes to trigger a custom "load" event.

谢谢

这篇关于Jquery偶尔会在图像上返回零高度和宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆