【问题标题】:Hide images on document ready, fade in each image as it is loaded隐藏文档上的图像准备好,在每个图像加载时淡入淡出
【发布时间】:2012-02-17 15:48:26
【问题描述】:

我正在尝试使用 setInterval 编写一个 Jquery 脚本,该脚本在加载图像时淡入淡出。

我当前的代码不起作用——“图像加载”类没有被删除。

所以有两个问题:1)为什么代码不起作用,以及 2)这是完成我想做的事情的最佳方式吗?有没有更好的办法?

   (function($) {

        var $props = $('#properties'),
            $imgs = $props.find("img");

        $imgs.addClass('image-loading');

        (function updateImages() {
            setTimeout(function() {

                $imgs.each(function(){
                    $me = $(this);

                    // If image is loaded, remove class
                    $me.load(function(){
                        $me.removeClass('image-loading');
                    });
                });

                // if all images are loaded, stop the loop
                $imgs.load(function () {
                    return false;
                });

                updateImages();
            }, 100);
        })();

    })(jQuery);

【问题讨论】:

标签: jquery load


【解决方案1】:

这看起来像是部分实现。试试这个:

(function($) {

    var $props = $('#properties'),
        $imgs = $props.find("img"),
        loadCounter = 0, // you init these, but never use them?
        nImages = $imgs.length;

    $imgs.addClass('image-loading');

    (function updateImages() {
        setTimeout(function() {
            $imgs.one("load", function() {

                $(this).removeClass('image-loading');

            // to manually trigger onload if image is in cache
            }).each(function () {
                if (this.complete) {
                    $(this).trigger("load");
                }
            });
            updateImages();
        }, 100);
    })();

})(jQuery);​

Demo here.

【讨论】:

    【解决方案2】:

    我有一个插件可以帮助你。包含jQuery preloadImages 插件,然后尝试以下代码:

    properties.preloadImages(function(){
      // this refers to the image that is done loading.
      $(this).removeClass("image-loading");
    })/*.done(function(){
      alert("All images are loaded!");
    })*/;
    

    编辑澄清:
    此代码将替换 (function updateImages(){...})()

    【讨论】:

      【解决方案3】:

      我最终使用了以下 jQuery 插件:

      https://github.com/farinspace/jquery.imgpreload

      语法超级简单:

              var $imgs = $('#properties').find("img");
      
              $imgs.imgpreload({
                  each: function() {
                      $(this).removeClass('image-loading');
                  }
              });
      

      与我最初尝试编写的代码相比,它的重量更轻、更简单。它完全符合我的要求。

      【讨论】:

        猜你喜欢
        • 2011-11-16
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        • 2014-06-13
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        相关资源
        最近更新 更多