我的图像已完成加载,但其高度和宽度尚未更新。什么时候会发生这种情况?
我正在使用 jQuery 插件,一旦加载页面上的所有图像,就会调用回调。它检查 imageObject.complete 属性并将处理程序绑定到 load 和 error 事件以确定图像加载何时完成。
这效果很好,但我遇到的问题是,即使图像被视为已加载,当我检查图像或其图像的 height
和 width
属性时包含 div
元素,尺寸尚未更新。
这是一个示例:
如何确保在尝试访问其高度
和宽度
尺寸之前,包含元素是否已调整大小以适合图像?
编辑1:我清理并注释了我的jsfiddle中的代码,以使示例更容易理解。
编辑2:必须存在基于缓存的竞争条件或变化,因为当我从不同的机器运行代码时,它可以正常工作(即,正确计算顶部边距),这实际上是<强>不好因为它不一致。这种不一致在 Chrome、FWIW 中更为明显。
另外,需要明确的是,目标不是每次加载图像时都调用 init
;而是调用 init 。相反,在通过 AJAX load
调用加载所有图像后,应调用 init 一次。
I'm using a jQuery plugin that invokes a callback once all images on page have been loaded. It checks the imageObject.complete
property and binds a handler to the load
and error
events to determine when image loading is done.
This works well, but the problem I'm running into is that, even though an image is considered loaded, when I inspect the height
and width
properties of the image or its containing div
element, the dimensions have not yet been updated.
Here's an example:
How can I ensure that the containing element has been resized to fit the image before attempting to access its height
and width
dimensions?
EDIT 1: I cleaned up and commented the code in my jsfiddle to make the example easier to understand.
EDIT 2: There must be a race condition or variation based on caching because when I run the code from a different machine, it works properly (i.e., the top margin is calculated properly), which is actually not good because it is not consistent. The inconsistencies are more apparent in Chrome, FWIW.
Also, to be clear, the goal isn't to call init
every time an image loads; rather, init
should be called once after all images have been loaded via the AJAX load
invocation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案:http://jsfiddle.net/morrison/RtnVx/30/< /strong>
在图像加载完成之前,您不需要调用batchImageLoad
。我在加载的图像上创建了一个事件。更新的注释:
error
事件提供错误处理,插件也是如此。#slides
开始的所有img
并将该长度存储在.data()
属性以及变量来保存已加载的数量。img
上绑定load
和error
事件,以更新加载图像的数量。setTimeout()
直到所有图像的宽度都大于零,然后触发init()
。Answer: http://jsfiddle.net/morrison/RtnVx/30/
You needed to not callbatchImageLoad
until the image was done loading. I created an event on the loaded image.Updated Notes:
error
event, as did the plug-in.img
's descending from#slides
and store that length in a.data()
attribute, as well as a variable to keep how many have loaded.load
anderror
events on eachimg
which updates the count of loaded images.setTimeout()
until all of them have widths greater than zero then fireinit()
.