原理:当img标签中有src时,它就会试图去加载src中的内容,实现一次请求。而我们不再img中写src,而是data-src(也可以是别的名字)只在图片滚动到屏内视野中时,将data-src的内容加到src中完成请求和加载。这样类似于图很多的首页面打开时不会一股脑请求所有图片,而是翻到哪加载到哪
以下代码全贴进去可以运行。
并实现了附加功能,如果你的图片路径错误不能加载,左上角会出现一个丑丑的image not found的小图标,解决办法就是添加 onerror="errorFn(this)"
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.con{
background: #eee;
}
.con .nav-con-yard-item{
width:100%;
background: #fff;
border:1px solid #333;
margin-bottom: 15px;
}
.con .nav-con-yard-item img{
display: inline-block;
width:100%;
height:120px;
background: #f2f2f2;
}
</style>
</head>
<body>
<script>
function errorFn(this_) {
this_.src='https://static.nalada.cn/yard/20180810/1226556810.jpeg'
}
</script>
<div class="con">
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1226556810.jpeg" data-alt="7号院室外" onerror="errorFn(this)"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180804/2336404103.jpeg" alt="7号院室外"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180804/2336404001.jpeg" alt="7号院客厅"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1226552426.jpeg" alt="7号院室外"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180804/2336402007.jpeg" alt="7号院客厅"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1226556236.jpeg" alt="7号院卧室"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1226552390.jpeg" alt="7号院卧室"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180804/2336409343.jpeg" alt="7号院卧室"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1229592601.jpeg" alt="7号院卧室"></div>
<div class="nav-con-yard-item"><img data-src="https://static.nalada.cn/yard/20180810/1226559846.jpeg" alt="7号院卫生间"></div>
</div>
<script src="../../../static/list/jquery-1.12.4.min.js"></script>
<script>
$(window).scroll(function (e) {
var screenTop = parseFloat($(this).scrollTop());
imglazyoadFn(screenTop);
});
function imglazyoadFn(screenTop) {
$('[data-src]').each(function (k,v) {
var isCanLoad = screenTop+parseFloat($(window).height())> parseFloat($(v).offset().top);
if(isCanLoad){
$(v).attr('src',$(v).attr('data-src'));
$(v).attr('alt',$(v).attr('data-alt'));
}
});
}
imglazyoadFn(0);
function errorFn(this_) {
this_.src='http://img.sccnn.com/bimg/338/24556.jpg';
}
</script>
</body>
</html>
网友评论