我看到
a comment on Ben Nadel’s blog在哪里Stephen Rushing发布了一个装载机,但我无法弄清楚我如何能够通过选择器和参数..
我想我也需要一个完整的errorCallback函数?
我想我也需要一个完整的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()是因为某些浏览器不会从缓存中获取的图像触发加载事件,这就是您发布的示例中的轮询尝试做的事情.