2

可能重复:
jQuery 检查图像是否已加载

我有以下标记的情况:

<div class="image">
    <img class="" src="content-images/1.jpg">
    <span class="slide" rel="content-images/2.jpg"></span>
    <span class="slide" rel="content-images/3.jpg"></span>
    <span class="slide" rel="content-images/4.jpg"></span>
</div>

现在在 CSS 中,所有的子div.image元素都是绝对定位的,所以它们彼此堆叠在一起。

我正在做的是,在某个触发器上,假设当在页面上的其他位置单击按钮时,将span's更改为 ' imgs 并在每个跨度中src设置为 the 。rel这些图像是大型高分辨率图像,因此它们可能需要一段时间才能完全加载。

使用 javascript / jQuery 我需要显示从单击按钮到所有span' 被替换为img' 完成加载的加载消息/指示器。

.load()由于图像和缓存等方面的已知问题,我无法使用 jQuery 。

我尝试使用imagesloaded但它似乎没有做我需要的。

有没有其他方法可以做到这一点?

4

1 回答 1

0

我不太确定,如果这是你想要实现的,但你可以试一试......

$("#button").click(function(){
    console.log("Started loading...");
    // Get all spans to replace, and count them
    var imgSpans = $("div.image span.slide"), 
        toLoad = imgSpans.length,
        loaded = 0;
    // Now load each image
    for (var i = 0; i < toLoad; ++i) {
        // Closure to keep correct value of i
        (function(i){
            // Preload image
            var img = new Image();
            img.src = imgSpans.eq(i).attr("rel");
            img.onload = function(){
                // When loading has finished, replace span with img...
                imgSpans.eq(i).replaceWith(img);
                if (++loaded == toLoad) {
                    // ...and check if all images have been loaded by now
                    console.log("Finished loading...");
                }
            };
        })(i);
    }
});

演示(JSFiddle)

于 2012-10-06T23:39:10.900 回答