【问题标题】:What's a good technique for displaying a "loading..." image?显示“正在加载...”图像的好技术是什么?
【发布时间】:2010-09-23 03:30:55
【问题描述】:

我正在使用一个div,其中包含任意数量的img 元素。现在,每个 img 都有以下 CSS:

#content > img {
display: none;
position: absolute;
top: 0px;
left: 0px;
}

并且可以通过依次显示和隐藏图像的功能循环显示图像。但是,在加载每个图像时,我想显示一个“正在加载...”图像。我想使用 JavaScript/jQuery 将每个不完整图像的源交换为“正在加载...”图像同时仍然允许它加载。什么是精益求精的方法?

【问题讨论】:

    标签: javascript jquery image-loading


    【解决方案1】:
    $(function(){
       $('<img>').attr('src','loading.gif'); // preload the "loading" image.
    
       $('#content > img').each(function(){
           var original = this.src;
           var $this = $(this);
           $this.attr('src','loading.gif'); // swap to loading image.
           $('<img>').attr('src',original)// pre-load original.
                  .load(function(){
                     $this.attr('src',original); // swap it back when pre-load is done. 
                  });
       })
    });
    

    crazy example

    【讨论】:

    • 现在一个想法。 $('&lt;img&gt;') 选择器中的&lt;&gt; 的用途是什么?除了选择 img 元素之外,这是否还有其他作用?
    【解决方案2】:

    有一个 imagesLoaded 插件可以在这里找到:http://gist.github.com/268257

    只显示加载图片,绑定imagesLoaded事件,当它被触发时,隐藏加载图片。

    更新:

    其实jQuery现在已经内置了检测加载的方法:http://api.jquery.com/load-event/

    【讨论】:

    • 是的,我知道这个插件。我想每次显示其中一张图像时我都可以执行一个函数。如果它不完整,则会显示“加载”图像(在div 前面)。否则不显示。本来想切换每张图片的来源,但我想没有必要。
    • 别忘了我们有 hideshow 方法。我认为 src 方式行不通,因为您需要将其设置为大图像才能开始下载。
    • @Matt - 我不太明白 - you'd need to have it set to the large image in order to start the download
    • 假设您有一个图像“/test.jpg”要显示。在您将 img 标签的 src 设置为“/test.jpg”之前,浏览器不会开始下载它。所以,如果你想通过 src 属性进行交换,你需要先将 src 属性设置为一些 other img 标签,所以你最好只做一次。
    • 呵呵,我给你介绍$('&lt;img&gt;')。让我们把/test.jpg 作为它的来源。 $('&lt;img&gt;').attr('src','/test.jpg')。这就像&lt;img src="/test.jpg" /&gt;。唯一的区别是$('&lt;img&gt;') 没有附加到DOM。酷;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2011-10-08
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多