Home > Web Front-end > JS Tutorial > body text

An example of lazy loading of images

零下一度
Release: 2017-06-29 11:36:07
Original
1475 people have browsed it

You will always see it on websites with many pictures. When you browse to that location, the picture there will be loaded.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			img{
				display: block;
				width: 500px;
				height: 300px;
			}
			div{
				margin: 500px 0 0 40px;
			}
		</style>
	</head>
	<body>
		<div id="banner">
			<img data-src="image/01.jpeg">
			<img data-src="image/02.jpeg">
			<img data-src="image/03.jpeg">
			<img data-src="image/04.jpeg">
			<img data-src="image/05.jpg">
			<img data-src="image/06.png">
			<img data-src="image/07.png">
			<img data-src="image/08.png">
		</div>

		<script type="text/javascript">
			window.onload=function(){
				var banner=document.getElementById("banner"); 
				var imgs=banner.getElementsByTagName("img");
				 add();//页面加载完成先执行一次
				function getTop(obj){ //写一个方法获取图片距离top的值
					var t=0;      //定义一个保存top值的 变量
					while(obj){  //循环获取每个父级定位的top值
						t+=obj.offsetTop;  //获取传入或改变父级定位的top值,当到大body的时候没有 他的父级定位为null所以就停了
						obj=obj.offsetParent; //获取obj的父级定位
						console.log(t)
						console.log(obj)
					}
					return t;
				}
				function add(){
					var S = document.documentElement.scrollTop || document.body.scrollTop; //获取滑动条距top的值
					var H = window.innerHeight; //获取显示区域高度(只读)
					for(var i=0;i<imgs.length;i++){  //循环图片
						if((S+H) > getTop(imgs[i])){ 判断图片是否进入可视区域
							imgs[i].setAttribute("src",imgs[i].getAttribute("data-src")); //当进入的时候给src 赋值
						}
					}
				}
				
				window.onscroll=function(){ //每次滚动运行方法判断
					add()
				}
			}
				
				
				
			
		</script>
	</body>
</html>
Copy after login

 

The above is the detailed content of An example of lazy loading of images. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template