美文网首页
js懒加载思想和单张图片的懒加载

js懒加载思想和单张图片的懒加载

作者: SmallTwo | 来源:发表于2017-04-18 18:12 被阅读33次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            #box{
                margin-top: 800px;
                width: 300px;
                height: 200px;
                background: red;
            }
            #img{
    
                width: 90%;
                height: 90%;
            }
        </style>
    </head>
    
    <body>
    <div id="box">
        <img src="" alt="" id='img' data-origion="http://cdnimg2.edu.euming.com/pkuie/20151128/s_1448682060094_T0iGqY.jpg@480w">
    
    </div>
    <script>
        var box = document.getElementById('box'),imgs = document.getElementById('img');
        var imgH = parseFloat(getComputedStyle(imgs,null).height) + imgs.offsetTop;
    
        window.onscroll = function () {
            var scrolH = (document.documentElement.clientHeight || document.body.clientHeight) + (document.documentElement.scrollTop || document.body.scrollTop);
            if (imgs.loaded) return;
    
            if (imgH < scrolH) {
            console.log('haha');
                var newImage = new Image;
                newImage.src = imgs.getAttribute('data-origion');
                newImage.onload = function () {
                    imgs.src = this.src;
                    newImage = null;
                    imgs.loaded = true;
                }
    
            }
        }
    
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:js懒加载思想和单张图片的懒加载

          本文链接:https://www.haomeiwen.com/subject/jdrqzttx.html