我看到了a comment on Ben Nadel's blog Stephen Rushing 发布了一个加载器,但我不知道如何传递选择器和参数...
我想我还需要 completeCallback
和 errorCallback
函数?
function imgLoad(img, completeCallback, errorCallback) {
if (img != null && completeCallback != null) {
var loadWatch = setInterval(watch, 500);
function watch() {
if (img.complete) {
clearInterval(loadWatch);
completeCallback(img);
}
}
} else {
if (typeof errorCallback == "function") errorCallback();
}
}
// then call this from anywhere
imgLoad($("img.selector")[0], function(img) {
$(img).fadeIn();
});
HTML:
<a href="#" class="tnClick" ><img id="myImage" src="images/001.jpg" /></a>
JS:
$(document).ready(function() {
var newImage = "images/002.jpg";
$("#myImage").css("display","none");
$("a.tnClick").click(function() {
// imgLoad here
});
})
最佳答案
如果您希望它在显示之前加载,您可以将其削减很多,如下所示:
$(document).ready(function() {
var newImage = "images/002.jpg"; //Image name
$("a.tnClick").click(function() {
$("#myImage").hide() //Hide it
.one('load', function() { //Set something to run when it finishes loading
$(this).fadeIn(); //Fade it in when loaded
})
.attr('src', newImage) //Set the source so it begins fetching
.each(function() {
//Cache fix for browsers that don't trigger .load()
if(this.complete) $(this).trigger('load');
});
});
});
.one()
调用确保 .load() 仅触发一次,因此不会出现重复的淡入。最后的 .each()
是因为某些浏览器不会为从缓存中获取的图像触发 load
事件,这就是您发布的示例中的轮询内容也正在努力做到这一点。
关于jQuery 加载图像并带有完整的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392410/