【问题标题】:Lazyload background image, remove data-src onload延迟加载背景图片,去掉data-src onload
【发布时间】:2018-08-08 18:03:35
【问题描述】:

我正在尝试在页面上延迟加载多个背景图像。我从数据属性data-src 中获取背景图像。加载图片后,我想删除 data-src 数据属性:

$(window).on('load', function() {

    $.fn.loadbgimg = function () {
        $('.jumbo[data-src]').each(function(index) {

            var top_of_object = $(this).offset().top;
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object in the window */
            if( bottom_of_window > top_of_object ) {   

                // get datasrc  
                datasrc = $(this).data('src'); 

                // replace bg with data-src
                $(this).css("background-image", "url('" + datasrc + "')"); 

                // remove data-src when img loaded
                $(this).on('load', function() {

                   $(this).removeAttr('data-src');

                });


            }
        });
    };

    $('.jumbo').loadbgimg();

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        $('.jumbo').loadbgimg();

    });

});

除了最后一部分“加载 img 时删除 data-src”外,一切似乎都正常。这是无所作为。数据属性没有被删除。有什么想法吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    背景图片没有加载事件。解决这个问题的正常方法是创建一个图像元素,不要将其添加到 DOM 中,而是设置 src 属性。然后处理它的加载事件,并在加载时设置背景图像 url。因为您已经加载了图像,它将使用您的缓存,而不是再次下载它。您可以在此时删除 data-src 属性。

    这是一个例子......

    var $this = $(this);
    var datasrc = $this.data('src'); 
    
    // create an image so we have something with a load event
    var $img = $("<img/>");
    
    // handle the load event - remove the data-src attribute
    $img.on("load", function() {
    
        // replace bg with data-src
        $this.css("background-image", "url('" + datasrc + "')"); 
    
        // remove data-src when img loaded
        $this.removeAttr('data-src');
    });
    
    // load the image in memory
    $img.attr("src", datasrc);
    

    【讨论】:

    • 没问题 - 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    相关资源
    最近更新 更多