jQuery实现页面滚动图片按需加载(转载)

时间:2021-08-30 19:26:16
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery scrolling</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<!--imgbox-->
<div class="wrapper">
<div class="img-box">
<img src="img/1.png" />
</div>
<div class="img-box">
<img src="img/2.png" />
</div>
<div class="img-box">
<img src="img/3.png" />
</div>
<div class="img-box">
<img data-url="img/4.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/5.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/6.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/7.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/8.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/9.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/10.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/11.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/12.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/13.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/14.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/15.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/16.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/17.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/18.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/19.png" src="img/pix.png" />
</div>
<div class="img-box">
<img data-url="img/20.png" src="img/pix.png" />
</div>
</div>

<script src="js/jquery_1.9.js"></script>
<script src="js/main.js"></script>
</body>
</html>

*{
margin: 0;
padding: 0;
}
/*wrapper*/
.wrapper{
width: 500px;
height: 5000px;
margin: auto;
}
.img-box{
width: 100%;
margin-bottom: 20px;
padding-bottom: 10px;
height: 260px;
text-align: center;
border-bottom: 2px dashed #ccc;
}
$(function(){    var $wd = $(window),        $img = $('img'),        imgTop,          //图片距离顶部高度        scTop,             //滚动条高度        wH;           //窗口高度    wH = $wd.height();         //获得可视浏览器的高度    $wd.scroll( function() {        scTop = $wd.scrollTop();       //获取滚动条到顶部的垂直高度        $img.each(function(){            imgTop =  $(this).offset().top;            if(imgTop - wH < scTop &&     //图片必须出现在窗口底部上面                imgTop - wH > 0 &&        //排除首页图片                $(this).attr('src') != $(this).data('url')){          //排除已经加载过的图片                   $(this).attr({                       src: $(this).data('url')                   });            }        });    });});

原文链接:https://my.oschina.net/leipeng/blog/221911