jQuery 加载带有完整回调的图像 [英] jQuery loading images with complete callback

查看:33
本文介绍了jQuery 加载带有完整回调的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了 对 Ben Nadel 博客的评论,Stephen Rushing 在那里发布了一个加载器,但我不知道如何传递选择器和参数...

I saw a comment on Ben Nadel's blog where Stephen Rushing posted a loader, but I can't figure out how I can pass the selectors and parameter...

我想我还需要一个 completeCallbackerrorCallback 函数?

I think I also need a completeCallback and errorCallback functions?

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
    });
})

推荐答案

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

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.

这篇关于jQuery 加载带有完整回调的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆