js控制图片在可视区域才展示,图片懒加载

<img id="img3" src="" data-src="/home/SeeImg?file=3032b808396a28022d760c464241c194.jpg" style="height:100px;min-width: 32px" /> 

!function (w) {
    
    
        w.addEventListener('scroll', function () {
    
    
            watchImgShow();
        });

            /* 图片在可视区才展示  */
            w.watchImgShow = function () {
    
    
                //可见区域高度
                var clientHeight = document.documentElement.clientHeight;

                //滚动条滚动高度
                var scrollTop = document.documentElement.scrollTop;

                var scrollHeight = clientHeight + scrollTop;

                //  元素距离顶部高度
                //document.getElementById("k112").offsetTop;

                $("img[src='']").each(function (index, ele) {
    
    
                    /* 元素距离顶部高度 */
                    var dom_offsetTop = $(ele).offset().top;
                    if (scrollHeight >= dom_offsetTop) {
    
    
                        /* 元素进入可视区域 */
                        console.log(ele);
                        console.log("scrollHeight=" + scrollHeight + ",dom_offsetTop=" + dom_offsetTop);
                        
                        $(ele).attr("src", $(ele).attr("data-src"));
                        setTimeout(function (g) {
    
    
                            $(g).css("max-height", "100px");
                            $(g).css("height", "");
                        }, 100, ele);
                       
                    }
                });
            }
            watchImgShow();
         
           
}(window);

猜你喜欢

转载自blog.csdn.net/u011511086/article/details/132859213
今日推荐