-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlazyload.html
66 lines (64 loc) · 1.74 KB
/
lazyload.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片懒加载</title>
<style>
* {
margin: 0;
padding: 0;
}
img {
display: block;
width: 100%;
height: 300px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<img data-src="./images/1.png" alt="">
<img data-src="./images/2.png" alt="">
<img data-src="./images/3.jpg" alt="">
<img data-src="./images/4.png" alt="">
<img data-src="./images/5.png" alt="">
<img data-src="./images/6.png" alt="">
<img data-src="./images/7.jpg" alt="">
<img data-src="./images/8.png" alt="">
<img data-src="./images/9.png" alt="">
<img data-src="./images/10.png" alt="">
<img data-src="./images/1.png" alt="">
<img data-src="./images/2.png" alt="">
<script>
/**
* 获取窗口高度
*/
function getWindowHeight () {
return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}
function getTop (e) {
var T = e.offsetTop;
while (e = e.offsetParent) {
T += e.offsetTop;
}
return T;
}
var delta = 30;
var imgs = document.querySelectorAll('img');
function lazyLoad (imgs) {
var h = getWindowHeight();
var s = document.documentElement.scrollTop || document.body.scrollTop;
for (var i=0, l=imgs.length; i<l; i++) {
if (h + s + delta > getTop(imgs[i])) {
!imgs[i].src && (imgs[i].src = imgs[i].getAttribute('data-src'));
}
}
}
window.onload = window.onscroll = function () {
lazyLoad(imgs);
};
</script>
</body>
</html>