且构网

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

jQuery加载完整回调的图像

更新时间:2023-12-04 23:07: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.