2011-09-28 73 views
5

我想上预装的Click事件图片:JavaScript图片对象 - 处理onload事件

// 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 - 任何知道我在这里失踪?

回答

10

.complete是图像对象的属性,而不是您可以附加到的事件。使用onload事件:

var image = new Image(); 
image.onload = function() { 
    alert('image loaded'); 
}; 
image.src = document.URL + 'image/image.jpg'; 

注:务必设置源属性之前附加到onload事件处理程序。

说明解释:图像缓存。如果图像被缓存,那么onload事件将立即触发(有时在设置处理程序之前)

+0
+1

它可以在你的点击处理程序中... –

+0

为什么在src属性设置之前调用它很重要? – user398341