javascript jQuery 检查图像是否已加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5404335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery check if image is loaded
提问by Francisc
I need help with the following code which doesn't work:
我需要有关以下不起作用的代码的帮助:
var timeoutID=0; var currentImage=0;//first image is position 0 in arrImages array var arrImages=[bla bla bla array of image URLs]; function slideShow() { if($('#myImg').complete)// <------- Here is where it fails as that's UNDEFINED. { //curentImage is a global var that remebembers the on-screen image array key var nextImage=currentImage+1; //arrImages is the array of image URLs if(nextImage>=arrImages.length){nextImage=0;} $('#myImg').attr('src',nextImage); clearTimeout(timeoutID); //Change image each second after previous image was loaded timeoutID=setTimeout("slideShow()",1000); } else { $('#myImg').load(slideShow); } }
Basically I want to change the src for #myImg each second, provided that the counter starts after the image loaded.
基本上我想每秒更改 #myImg 的 src,前提是计数器在图像加载后启动。
*I hate the code button in the text editor for Stack Overflow!
*我讨厌 Stack Overflow 的文本编辑器中的代码按钮!
回答by Sang
'complete' is for native javascript object. so you should get javascript object from jQuery. like,
'complete' 用于本机 javascript 对象。所以你应该从 jQuery 获取 javascript 对象。喜欢,
$('#myImg')[0].complete
or
或者
$('#myImg').get(0).complete
回答by Domen Grabec
If I remember correctly the image gets the width and height when it gets loaded. So I guess you could check the width if the image. And as long as that is 0 the image is not loaded.
如果我没记错的话,图像在加载时会获得宽度和高度。所以我想你可以检查图像的宽度。只要它是 0,就不会加载图像。