原生js实现懒加载

<!DOCTYPE html>
<html>
<head>
  	<meta charset="utf-8">
  	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  	<title>开始使用layui</title>
  	<style type="text/css">
		.img-box{
			width: 100px;
			margin: 0 auto;
		}
		.img-block{
			width: 100px;
			height: 120px;
			text-align: center;
			line-height: 20px;
			margin-bottom: 10px;
		}
		.img-block img{
			width: 100%;
			height: 100px;
		}
	</style>
</head>
<body>
 
 	<div class="img-box">
		
 	</div>

<!-- 你的HTML代码 -->
<script src="js/jquery.min.js"></script>
<script>
	$(document).ready(function(){
		var data = [
			{src: "images/face/0.gif", title: "第一张"},
			{src: "images/face/1.gif", title: "第二张"},
			{src: "images/face/2.gif", title: "第三张"},
			{src: "images/face/3.gif", title: "第四张"},
			{src: "images/face/4.gif", title: "第五张"},
			{src: "images/face/5.gif", title: "第六张"},
			{src: "images/face/6.gif", title: "第七张"},
			{src: "images/face/7.gif", title: "第八张"},
			{src: "images/face/8.gif", title: "第九张"},
			{src: "images/face/9.gif", title: "第十张"},
			{src: "images/face/10.gif", title: "第十一张"},
			{src: "images/face/11.gif", title: "第十二张"},
			{src: "images/face/12.gif", title: "第十三张"},
			{src: "images/face/13.gif", title: "第十四张"},
			{src: "images/face/14.gif", title: "第十五张"},
			{src: "images/face/15.gif", title: "第十六张"},
			{src: "images/face/16.gif", title: "第十七张"}
		];

		for (var i = 0; i < data.length; i++) {
			var html = "<div class='img-block'><img data-src='" + data[i].src + "'><div>"+data[i].title+"</div></div>";
			$(".img-box").append(html);
		}

		var winTop = window.innerHeight;
		var imgs = document.querySelectorAll('img');
		scrollEvent();

		window.onscroll = function(){
			scrollEvent();
		}

		function scrollEvent(){
			var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
			//console.log(scrollTop);
			for(var i=0;i < imgs.length;i++){
				if(imgs[i].offsetTop < scrollTop + winTop ){//滚动条到顶部的高度+窗口的高度>img元素到顶部的高度
					imgs[i].src = imgs[i].getAttribute('data-src');
				}
			}
		}
	})
</script> 
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专业前端小白

写了这么久文章,1分钱都没收到

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值