关于图像加载 IE 问题的 JavaScript/jQuery 事件侦听器
我正在寻找一种方法来为尽可能多的浏览器实现此功能:
var image = new Image();
image.addEventListener("load", function() {
alert("loaded");
}, false);
image.src = "image_url.jpg";
这在 IE 中不起作用,所以我用 google 搜索并发现 IE 低于 9 不支持 .addEventListener()
。我知道有一个名为 .bind()
的 jQuery 等效项,但它不适用于 Image()
。我需要更改什么才能使其在 IE 中也正常工作?
I am looking for a way to implement this for as many browsers as possible:
var image = new Image();
image.addEventListener("load", function() {
alert("loaded");
}, false);
image.src = "image_url.jpg";
This didn't work in IE so I googled and found out that IE's lower than 9 do not support .addEventListener()
. I know there is a jQuery equivalent called .bind()
but that doesn't work on an Image()
. What do I have to change for this to work in IE too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
IE 支持 AttachEvent。
使用 jQuery,您可以只编写
事件,如果您有可能使用 jQuery,我建议使用它,因为它将照顾浏览器兼容性。您的代码将在所有主要浏览器上运行,您不必担心这一点。
另请注意,为了在 IE 中触发 load 事件,您需要确保不会从缓存中加载图像,否则 IE 将不会触发 load 事件。
为此,您可以在图像 url 的末尾附加一个虚拟变量,如下所示
使用 jQuery load 方法的一些已知问题是
有关详细信息,请参阅 jQuery 文档。
IE supports attachEvent instead.
With jQuery, you can just write
When it comes to events, if you have the possibility of using jQuery I would suggest using it because it will take care of browser compatibility. Your code will work on all major browser and you don't have to worry about that.
Note also that in order to the load event being fired in IE, you need to make sure the image won't be loaded from the cache, otherwise IE won't fire the load event.
To do this, you can append a dummy variable at the end of the url of your image, like this
Some known issues using the jQuery load method are
See the jQuery docs for more info.
您必须使用
.attachEvent()
而不是.addEventListener()
。You have to use
.attachEvent()
rather than.addEventListener()
.您可以使用
attachEvent
,但我会更喜欢添加addEventListener
侦听器 你自己。以下是该 MDN 链接上用于添加事件侦听器的代码:You can use
attachEvent
, but I would rather prefer you would add theaddEventListener
listener yourself. Here is the code on that MDN link for adding the event listener:new Image
基本上返回一个标签,因此您可以在 jQuery 中进行编码,如下所示: http://jsfiddle.net/pimvdb/LAuUR/1/。
编辑:在加载有效图像的情况下
new Image
basically returns an<img>
tag, so you can code in jQuery like: http://jsfiddle.net/pimvdb/LAuUR/1/.EDIT: in case of loading valid images
现在最好的方法可能是使用 jQuery 和 jQuery 插件 imagesLoaded 而不是 jQuery 的内置
load()
或纯 JS。该插件负责处理 jQuery 文档提到的各种浏览器怪癖,即关于缓存图像并在新图像的src
相同时重新触发回调。只需下载 jquery.imagesloaded.min.js,添加将其与放在一起就可以了:
The best way to do it now is probably to use jQuery and the jQuery plugin imagesLoaded instead of jQuery's built-in
load()
or plain JS. The plugin takes care of the various browser quirks that the jQuery docs refer to, namely regarding cached images and re-firing the callback if the new image'ssrc
is the same. Just download jquery.imagesloaded.min.js, add it in with<script src="jquery.imagesloaded.min.js"></script>
and you're good to go: