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

标签 jquery image

我看到了a comment on Ben Nadel's blog Stephen Rushing 发布了一个加载器,但我不知道如何传递选择器和参数...

我想我还需要 completeCallbackerrorCallback 函数?

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() 是因为某些浏览器不会为从缓存中获取的图像触发 load 事件,这就是您发布的示例中的轮询内容也正在努力做到这一点。

关于jQuery 加载图像并带有完整的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392410/

相关文章:

python - 将图像中的白色像素更改为不同的颜色

javascript - 通过触发和图片点击机制切换div

jquery - 根据子图片高度改变父div高度,不超过父div max-width

image - 我可以使用图像在 Bootstrap 中触发模态窗口吗?

php - 合并图像 PHP

python - 在图像中绘制标记

css - RackSpace 到 css/stylesheet 图片的相对路径

Javascript 导致浏览器挂起

Jquery无法选择div

javascript - 查找是否有可见的 QTips?