图片懒加载DEMO

图片懒加载原理

从这张图片我们可以看出imgBox上边框到body上边框的距离(也即是 offset(imgBox))是不会变的,当滚动条滚动的时候,body.scrollTop在增加。。。

A = imgBox.offsetHeight + offset(imgBox).top

B = HTML.clientHeight + HTML.scrollTop

当 B >= A 时,图片刚好全部显示,开始加载.....

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* reset css */
        
        * {
            padding: 0;
            margin: 0;
        }
        
        img {
            border: none;
        }
        
        html,
        body {
            height: 1000%;
        }
        
        .imgBox {
            background-color: antiquewhite;
            height: 550px;
            width: 800px;
            margin: 800px auto;
            background-color: bisque;
        }
        
        img[src=""] {
            display: none;
        }
        
        .imgBox img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div class="imgBox">
        <img src="" data-img="https://www.nchu.edu.cn/Upload/main/ContentManage/Article/image/2019/06/02/c5cef8dbcbea471baa923972eba98921.jpg" alt="">
    </div>
    <script>
        // 获取当前元素到body的左偏移和右偏移
        function offset(curElem) {
            let parent = curElem.offsetParent,
                left = curElem.offsetLeft,
                top = curElem.offsetTop;
            while (parent && parent.tagName !== 'BODY') {
                left += parent.offsetLeft;
                top += parent.offsetTop;
                parent = parent.offsetParent;
            }
            return {
                left: left,
                top: top
            }
        }
        // 挂载真实的图片地址
        function lazyImg(img) {
            if (img.isLoaded) return;
            let imgUrl = img.getAttribute('data-img');
            img.src = imgUrl;
            img.onload = function() {
                img.style.display = 'block';
            }
            img.isLoaded = true;
        }
        let imgBox = document.querySelector('.imgBox'),
            _img = document.querySelector('img');

        window.onscroll = function() {
            let HTML = document.documentElement,
                A = HTML.scrollTop + HTML.clientHeight,
                B = imgBox.offsetHeight + offset(imgBox).top;
            console.log(offset(imgBox).top);
            if (A >= B) {
                lazyImg(_img);
            }
        }
    </script>
</body>

</html>
posted @ 2021-02-18 17:25  HelloCoderRookie  阅读(90)  评论(0编辑  收藏  举报