blob: 1b280680030dafdf212f98399e13dbfe1cbe7375 (
plain)
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
|
---
title: 'Document: scroll event'
slug: Web/API/Document/scroll_event
tags:
- API
- DOM
- Event
- Reference
- Scroll
- requestAnimationFram
- 事件
- 参考
- 滚动
translation_of: Web/API/Document/scroll_event
---
<p>文档视图或者一个元素在滚动时,会触发元素的<strong><code>scroll</code></strong>事件。</p>
<table class="properties">
<thead>
</thead>
<tbody>
<tr>
<th>Bubbles</th>
<td>Yes</td>
</tr>
<tr>
<th>Cancelable</th>
<td>No</td>
</tr>
<tr>
<th>Interface</th>
<td>{{DOMxRef("Event")}}</td>
</tr>
<tr>
<th>Event handler property</th>
<td>{{DOMxRef("GlobalEventHandlers.onscroll", "onscroll")}}</td>
</tr>
</tbody>
</table>
<div class="blockIndicator note">
<p><strong>注意:</strong>在 iOS UIWebViews中, 滚动进行时不会触发 <code>scroll</code> 事件;只有当滚动结束后事件才会被触发。参见 <a href="https://github.com/twbs/bootstrap/issues/16202">Bootstrap issue #16202</a>。Safari 和 WKWebViews 则没有这个问题。</p>
</div>
<h2 id="示例">示例</h2>
<h3 id="Scroll_事件节流">Scroll 事件节流</h3>
<p>由于 <code>scroll</code> 事件可被高频触发,事件处理程序不应该执行高性能消耗的操作,如DOM操作。而更推荐的做法是使用 {{DOMxRef("Window.requestAnimationFrame()", "requestAnimationFrame()")}}, {{DOMxRef("WindowOrWorkerGlobalScope.setTimeout()", "setTimeout()")}} 或 {{DOMxRef("CustomEvent")}} 给事件节流,如下所述。</p>
<p>然而需要注意的是,输入事件和动画帧常常以差不多的频率被触发,因此以下优化常常不必要。这个例子使用 <code>requestAnimationFrame</code> 优化 <code>scroll</code> 事件。</p>
<pre class="brush: js">// 参见: http://www.html5rocks.com/en/tutorials/speed/animations/
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
// 根据滚动位置做的事
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});</pre>
<p>在 <code><a href="/en-US/docs/Web/API/Document/defaultView/resize_event">resize</a></code> 事件页面中查看更多类似的例子。</p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
</tr>
<tr>
<td>{{SpecName('DOM3 Events', '#event-type-scroll')}}</td>
<td>{{Spec2('DOM3 Events')}}</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("api.Document.scroll_event")}}</p>
<h2 id="参见">参见</h2>
<ul>
<li><a href="/en-US/docs/Web/API/Element/scroll_event">Element: <code>scroll</code> event</a></li>
</ul>
|