Nic*_*ver 107
您可以使用.load()事件处理程序,如下所示:
$("#myImg").load(function() {
alert('I loaded!');
}).attr('src', 'myImage.jpg');
Run Code Online (Sandbox Code Playgroud)
确保在设置源之前附加它,或者在附加处理程序以侦听它之前事件可能已被触发(例如从缓存加载).
如果这是不是可行的(设置src绑定后),一定要检查它的加载和启动它自己,是这样的:
$("#myImg").load(function() {
alert('I loaded!');
}).each(function() {
if(this.complete) $(this).load();
});
Run Code Online (Sandbox Code Playgroud)
Pet*_*tai 18
使用普通Javascript也很简单:
// Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
Run Code Online (Sandbox Code Playgroud)
我也一直在研究这个很长时间,并发现这个插件可以很好地帮助解决这个问题:https : //github.com/desandro/imagesloaded
这似乎是一大堆代码,但是......我没有找到其他方法来检查图像何时加载。
使用 jQuery on('load') 函数是检查图像是否已加载的正确方法。但请注意,如果图像已在缓存中,则 on('load') 函数将不起作用。
var myImage = $('#image_id');
//check if the image is already on cache
if(myImage.prop('complete')){
//codes here
}else{
/* Call the codes/function after the image is loaded */
myImage.on('load',function(){
//codes here
});
}
Run Code Online (Sandbox Code Playgroud)