图片懒加载

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>图片懒加载</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .img-item {
             612px;
            height: 238px;
            overflow: hidden;
            margin: 10px auto;
            background-color: #ccc;
        }

        .img-item img {
            display: none;
             100%;
        }
    </style>
</head>

<body>
    <div class="container"></div>
</body>
<script src="./js/jquery-2.2.1.min.js"></script>
<script>
    $(function () {
        var imgArr = [
            'https://goss.veer.com/creative/vcg/veer/612/veer-164919552.jpg',
            'https://goss.veer.com/creative/vcg/veer/800water/veer-136695603.jpg',
            'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=186602880,1005592543&fm=26&gp=0.jpg',
            'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3577773561,2706257243&fm=26&gp=0.jpg',
            'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2366557490,3976512943&fm=11&gp=0.jpg',
            'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3743690184,2535555305&fm=26&gp=0.jpg',
            'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2575134299,1875583637&fm=26&gp=0.jpg',
        ],
            strHtml = '',
            imgArrLength = imgArr.length,
            $window = $(window),
            $container = $('.container');
        for (var i = 0; i < imgArrLength; i++) {
            strHtml += '<div class="img-item">' +
                '<img src="" isLoad="false" alt="" src-data="' + imgArr[i] + '">' +
                '</div>'
        }
        $container.html(strHtml);
        $imgItems = $container.children('.img-item');
        $window.on('load scroll', function () {
            $B = $window.outerHeight() + $window.scrollTop();
            $imgItems.each(function (index, item) {
                var $imgItem = $(item),
                    $imgItemA = $imgItem.outerHeight() + $imgItem.offset().top,
                    $img = $imgItem.children('img'),
                    isLoad = $img.attr('isLoad');
                if ($imgItemA <= $B && isLoad != 'true') {
                    console.log('懒加载图片');                    
                    $img.attr({
                        'src': $img.attr('src-data'),
                        'isLoad': true
                    }).stop().fadeIn();
                }
            })

        })
    })
</script>

</html>
原文地址:https://www.cnblogs.com/mishiyang/p/12612335.html