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

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

问题描述

我看到评论Ben Nadel的博客 Stephen Rushing发布了一个加载器,但我无法弄清楚如何通过选择器和参数..
我想我还需要一个完整的回调& errorCallback函数?

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.. I think I also need a completeCallback & 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天全站免登陆