Javascript图像对象 - 处理onload事件 [英] Javascript Image Object - Handle onload Event
本文介绍了Javascript图像对象 - 处理onload事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在点击事件上预加载图片:
I'm trying to preload image on click event:
// new image object
var imgObject = new Image();
// assign the path to the image to the src property
imgObject.src = document.URL + 'image/image.jpg';
// check if image has loaded
if (imgObject.complete) {
但完成调用永远不会在第一次点击时返回true - 任何想法我在这里缺少什么?
But the complete call never returns true on the first click - any idea what I'm missing here?
推荐答案
.complete
是图像对象的属性,而不是可以附加到的事件。使用 onload
事件:
.complete
is a property of the image object, not an event that you can attach to. Use the onload
event:
var image = new Image();
image.onload = function() {
alert('image loaded');
};
image.src = document.URL + 'image/image.jpg';
注意:请务必在设置来源之前附加到onload hander属性。
Note: Be sure to attach to the onload hander before setting the source attribute.
注释说明:图像缓存。如果图像被缓存,则onload事件将立即触发(有时在设置处理程序之前)
Note Explanation: Image caching. If the image is cached then the onload event will fire immediately (sometimes before setting the handler)
这篇关于Javascript图像对象 - 处理onload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文