且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery 加载带有完整回调的图像

更新时间:2023-12-04 22:54:52

如果你想让它在显示前加载,你可以把它删减很多,像这样:

If you want it to load before showing, you can trim that down a lot, like this:

$(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 事件,这就是您发布的示例中的轮询也在努力做到.

The .one() call makes sure .load() only fires once, so no duplicate fade-ins. The .each() at the end is because some browsers don't fire the load event for images fetched from cache, this is what the polling in the example you posted is trying to do as well.