FFi*_*ish 10 jquery load image complete
我在Ben Nadel的博客上发表评论,其中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();
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<a href="#" class="tnClick" ><img id="myImage" src="images/001.jpg" /></a>
Run Code Online (Sandbox Code Playgroud)
JS:
$(document).ready(function() {
var newImage = "images/002.jpg";
$("#myImage").css("display","none");
$("a.tnClick").click(function() {
// imgLoad here
});
})
Run Code Online (Sandbox Code Playgroud)
Nic*_*ver 40
如果你想在显示之前加载它,你可以减少很多,如下所示:
$(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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
该.one()
调用确保.load()仅触发一次,因此没有重复的淡入.将.each()
在年底是因为有些浏览器不火load
从缓存中获取图像的事件,这是在本例中您发布的投票正在试图做的一样好.