# IntersectionObserver
<div id="scrollArea" style="height:900px">
<div style="height:1000px"></div>
<div id="title">观察我吧</div>
<div style="height:1000px"></div>
<div>
<script>
let options = {
root: document.querySelector('#scrollArea'), // 根( root ) 元素,用于检查目标的可见性。必须是目标元素的父级元素。如果未指定或者为null,则默认为浏览器视窗。
rootMargin: '0px', // 属性(root)元素的外边距。类似于 CSS 中的margin属性,“ 10px 20px 30px 40px"(上、右、下、左。如果有根参数,则 rootMargin 也可以使用指定来取值。该根是如何使用的)根节点和元素的发生范围是什么时候的计算集,使用该属性可以控制每一边的边界或范围目标的发生范围。交接元素默认为0。
threshold: 1.0, //元素是元素的编号,也是元素的根值,也是目标和根的相交程度。如果你想要的属性值超过 25% 就在 root 的每一个级别执行一次,那么你可以指定一个范围[0, 0.25, 0.5, 0.75, 1]。默认值是 0(元素含义)。有一个目标)元素中,出现功能在该根执行。
}
// 创建一个观察者之后需要给定一个目标元素进行观察。
let observer = new IntersectionObserver(callback, options);
// 每当该目标满足 IntersectionObserver 指定的阈值,就被调用。
let title = document.querySelector('#title')
observer.observe(title)
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 可以运行的案例
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<style type="text/css">
body {
padding: 0;
margin: 0;
}
svg:not(:root) {
display: block;
}
.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}
.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}
.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}
</style>
<style type="text/css">
#box {
background-color: rgba(40, 40, 190, 255);
border: 4px solid rgb(20, 20, 120);
transition: background-color 1s, border 1s;
width: 350px;
height: 350px;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.vertical {
color: white;
font: 32px "Arial";
}
.extra {
width: 350px;
height: 350px;
margin-top: 10px;
border: 4px solid rgb(20, 20, 120);
text-align: center;
padding: 20px;
}
</style>
<title>Intersection Observer API - a_simple_example - code sample</title>
</head>
<body>
<div style="height: 1000px;"> </div>
<div id="box" style="background-color: rgb(40, 40, 190);">
<div class="vertical">
Welcome to <strong>The Box!</strong>
</div>
</div>
<div style="height: 1000px;"> </div>
<script>
let boxElement;
let prevRatio = 0.0;
const increasingColor = 'rgba(40, 40, 190, ratio)';
const decreasingColor = 'rgba(190, 40, 40, ratio)';
// Set things up
window.addEventListener('load', () => {
boxElement = document.querySelector('#box');
createObserver();
}, false);
function createObserver() {
const options = {
root: null,
rootMargin: '0px',
threshold: buildThresholdList()
};
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(boxElement);
}
function buildThresholdList() {
const thresholds = [];
const numSteps = 20;
for (let i = 1.0; i <= numSteps; i++) {
const ratio = i / numSteps;
thresholds.push(ratio);
}
thresholds.push(0);
return thresholds;
}
function handleIntersect(entries) {
entries.forEach((entry) => {
if (entry.intersectionRatio > prevRatio) {
entry.target.style.backgroundColor = increasingColor.replace('ratio', entry
.intersectionRatio);
} else {
entry.target.style.backgroundColor = decreasingColor.replace('ratio', entry
.intersectionRatio);
}
prevRatio = entry.intersectionRatio;
});
}
</script>
</body>
</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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<style type="text/css">
body {
padding: 0;
margin: 0;
}
svg:not(:root) {
display: block;
}
.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}
.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}
.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}
</style>
<style type="text/css">
body {
font-family: "Open Sans", "Arial", "Helvetica", sans-serif;
background-color: aliceblue;
}
.wrapper {
display: grid;
grid-template-columns: auto minmax(min-content, 1fr);
grid-template-rows: auto minmax(min-content, 1fr);
max-width: 700px;
margin: 0 auto;
background-color: aliceblue;
}
header {
grid-column: 1 / -1;
grid-row: 1;
background-color: aliceblue;
}
aside {
grid-column: 1;
grid-row: 2;
background-color: cornsilk;
padding: 5px 10px;
}
aside ul {
padding-left: 0;
}
aside ul li {
list-style: none;
}
aside ul li a {
text-decoration: none;
}
main {
grid-column: 2;
grid-row: 2;
margin: 0;
margin-left: 16px;
font-size: 16px;
}
article {
background-color: white;
padding: 6px;
}
article:not(:last-child) {
margin-bottom: 8px;
}
article h2 {
margin-top: 0;
}
.ad {
height: 96px;
padding: 6px;
border-color: #555;
border-style: solid;
border-width: 1px;
}
.ad:not(:last-child) {
margin-bottom: 8px;
}
.ad h2 {
margin-top: 0;
}
.ad div {
position: relative;
float: right;
padding: 0 4px;
height: 20px;
width: 120px;
font-size: 14px;
bottom: 30px;
border: 1px solid black;
background-color: rgba(255, 255, 255, 0.5);
}
</style>
<title>Timing element visibility with the Intersection Observer API - building_the_site - code sample</title>
</head>
<body>
<div class="wrapper">
<header>
<h1>A Fake Blog</h1>
<h2>Showing Intersection Observer in action!</h2>
</header>
<aside>
<nav>
<ul>
<li><a href="#link1">A link</a></li>
<li><a href="#link2">Another link</a></li>
<li><a href="#link3">One more link</a></li>
</ul>
</nav>
</aside>
<main>
</main>
</div>
<script>
/* eslint-disable indent */
/* eslint-disable no-unused-vars */
/* eslint-disable prefer-const */
let contentBox;
let nextArticleID = 1;
let visibleAds = new Set();
let previouslyVisibleAds = null;
let adObserver;
let refreshIntervalID = 0;
window.addEventListener('load', startup, false);
function startup() {
contentBox = document.querySelector('main');
document.addEventListener('visibilitychange', handleVisibilityChange, false);
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: [0.0, 0.75]
};
adObserver = new IntersectionObserver(intersectionCallback, observerOptions);
buildContents();
refreshIntervalID = window.setInterval(handleRefreshInterval, 1000);
}
function handleVisibilityChange() {
if (document.hidden) {
if (!previouslyVisibleAds) {
previouslyVisibleAds = visibleAds;
visibleAds = [];
previouslyVisibleAds.forEach(function(adBox) {
updateAdTimer(adBox);
adBox.dataset.lastViewStarted = 0;
});
}
} else {
previouslyVisibleAds.forEach(function(adBox) {
adBox.dataset.lastViewStarted = performance.now();
});
visibleAds = previouslyVisibleAds;
previouslyVisibleAds = null;
}
}
function intersectionCallback(entries) {
entries.forEach(function(entry) {
const adBox = entry.target;
if (entry.isIntersecting) {
debugger;
if (entry.intersectionRatio >= 0.75) {
adBox.dataset.lastViewStarted = entry.time;
visibleAds.add(adBox);
}
} else {
debugger;
visibleAds.delete(adBox);
if ((entry.intersectionRatio === 0.0) && (adBox.dataset.totalViewTime >= 60000)) {
replaceAd(adBox);
}
}
});
}
function handleRefreshInterval() {
debugger;
const redrawList = [];
visibleAds.forEach(function(adBox) {
const previousTime = adBox.dataset.totalViewTime;
updateAdTimer(adBox);
if (previousTime != adBox.dataset.totalViewTime) {
redrawList.push(adBox);
}
});
if (redrawList.length) {
window.requestAnimationFrame(function(time) {
redrawList.forEach(function(adBox) {
drawAdTimer(adBox);
});
});
}
}
function updateAdTimer(adBox) {
const lastStarted = adBox.dataset.lastViewStarted;
const currentTime = performance.now();
if (lastStarted) {
const diff = currentTime - lastStarted;
adBox.dataset.totalViewTime = parseFloat(adBox.dataset.totalViewTime) + diff;
}
adBox.dataset.lastViewStarted = currentTime;
}
function drawAdTimer(adBox) {
const timerBox = adBox.querySelector('.timer');
const totalSeconds = adBox.dataset.totalViewTime / 1000;
const sec = Math.floor(totalSeconds % 60);
const min = Math.floor(totalSeconds / 60);
timerBox.innerText = min + ':' + sec.toString().padStart(2, '0');
}
const loremIpsum = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing' +
' elit. Cras at sem diam. Vestibulum venenatis massa in tincidunt' +
' egestas. Morbi eu lorem vel est sodales auctor hendrerit placerat' +
' risus. Etiam rutrum faucibus sem, vitae mattis ipsum ullamcorper' +
' eu. Donec nec imperdiet nibh, nec vehicula libero. Phasellus vel' +
' malesuada nulla. Aliquam sed magna aliquam, vestibulum nisi at,' +
' cursus nunc.</p>';
function buildContents() {
for (let i = 0; i < 5; i++) {
contentBox.appendChild(createArticle(loremIpsum));
// if (!(i % 2)) {
// loadRandomAd();
// }
if (i == 3) {
loadRandomAd();
}
}
}
function createArticle(contents) {
const articleElem = document.createElement('article');
articleElem.id = nextArticleID;
const titleElem = document.createElement('h2');
titleElem.id = nextArticleID;
titleElem.innerText = 'Article ' + nextArticleID + ' title';
articleElem.appendChild(titleElem);
articleElem.innerHTML += contents;
nextArticleID += 1;
return articleElem;
}
function loadRandomAd(replaceBox) {
const ads = [{
bgcolor: '#cec',
title: 'Eat Green Beans',
body: 'Make your mother proud—they\'re good for you!'
},
{
bgcolor: 'aquamarine',
title: 'MillionsOfFreeBooks.whatever',
body: 'Read classic literature online free!'
},
{
bgcolor: 'lightgrey',
title: '3.14 Shades of Gray: A novel',
body: 'Love really does make the world go round...'
},
{
bgcolor: '#fee',
title: 'Flexbox Florist',
body: 'When life\'s layout gets complicated, send flowers.'
}
];
let adBox, title, body, timerElem;
const ad = ads[Math.floor(Math.random() * ads.length)];
if (replaceBox) {
adObserver.unobserve(replaceBox);
adBox = replaceBox;
title = replaceBox.querySelector('.title');
body = replaceBox.querySelector('.body');
timerElem = replaceBox.querySelector('.timer');
} else {
adBox = document.createElement('div');
adBox.className = 'ad';
title = document.createElement('h2');
body = document.createElement('p');
timerElem = document.createElement('div');
adBox.appendChild(title);
adBox.appendChild(body);
adBox.appendChild(timerElem);
}
adBox.style.backgroundColor = ad.bgcolor;
title.className = 'title';
body.className = 'body';
title.innerText = ad.title;
body.innerHTML = ad.body;
adBox.dataset.totalViewTime = 0;
adBox.dataset.lastViewStarted = 0;
timerElem.className = 'timer';
timerElem.innerText = '0:00';
if (!replaceBox) {
contentBox.appendChild(adBox);
}
adObserver.observe(adBox);
}
function replaceAd(adBox) {
let visibleTime;
updateAdTimer(adBox);
visibleTime = adBox.dataset.totalViewTime;
console.log(' Replacing ad: ' + adBox.querySelector('h2').innerText + ' - visible for ' + visibleTime);
loadRandomAd(adBox);
}
</script>
</body>
</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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# 好文推荐
← ascll unicode编码 性能分析 →