原生js 图片懒加载

2018-08-24  本文已影响9人  他大舅啊
<img class="cover-image" src=" " data-src="http://img.weixin.bjhzkq.com/images/mb/mb_30.jpg" alt="...">
       var imgs = document.querySelectorAll('.cover-image');
        function getTop(e) {
            var T = e.offsetTop;
            while(e = e.offsetParent) {
                T += e.offsetTop;
            }
            return T;
        }

        function lazyLoad(imgs) {
            var H = window.innerHeight;
            var S = document.documentElement.scrollTop || document.body.scrollTop;
            for (var i = 0; i < imgs.length; i++) {
                if (H + S > getTop(imgs[i])) {
                    imgs[i].src = imgs[i].getAttribute('data-src');
                }
            }
        }

        window.onload = window.onscroll = function () {
            lazyLoad(imgs);
        }
上一篇下一篇

猜你喜欢

热点阅读