我想设定一个条件,当图像加载时间超过 2 秒时,将该图像与另一图像交换。现在,我有一个 .on('error')
函数来检查图像 url,如果 url 错误,则交换该图像。但是,如果图像加载时间过长怎么办?当某些图像加载时间超过 2 秒时,我可以使用回调吗?
$('img').on('load', function() {
//do things here
})
.on('error', function() {
$(this).parent().css('background-image', 'url("/broken-image")');
$(this).parent().addClass('img-not-found');
})
.each(function() {
if(this.complete) {
console.log('completed here');
}else {
$(this).parent().css('background-image', 'url("/broken-image")');
$(this).parent().addClass('img-not-found');
}
});
最佳答案
您可以让它工作 - 使用图像的 onload
函数来确定图像实际上已完成加载:
var imageElement = document.getElementById("myImage");
var isImageLoaded = false;
imageElement.onload = function() {
isImageLoaded = true;
}
setTimeout(function() {
if (isImageLoaded === false) {
//2 seconds passed, no dice on the image!
}
}, 2000);
关于javascript - 设置加载时间过长时交换图像的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40185160/