javascript - jquery 用 img 替换 span 并检查加载的 img

标签 javascript jquery css image

<分区>

Possible Duplicate:
jQuery check if image is loaded

我有以下标记的情况:

<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 更改为 imgsrc 设置为每个跨度中的 rel。这些图像是高分辨率的大图像,因此可能需要一段时间才能完全加载。

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

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

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

你能想到其他方法吗?

最佳答案

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

$("#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);
    }
});

DEMO (JSFiddle)

关于javascript - jquery 用 img 替换 span 并检查加载的 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12762482/

相关文章:

javascript - 无法显示姓氏 facebook js sdk?

javascript - 通过 Office Javascript API 1.1 发表评论

javascript - 将文本区域的值保存在 cookie 中,然后重新加载页面

jQuery TreeTable (cubicphase) - 如何从动态添加扩展节点切换到静态添加?

在页面上加载项目时出现 Javascript 错误

javascript - 我怎样才能使这个弹跳球动画代码无限重复?

jquery - 制作 CSS3 渐变背景旋转

javascript - 应用所有变换矩阵

html - 几乎标准模式如何从标准模式更改渲染?

javascript - 如何使用钩子(Hook)更改数组的状态?