scroll 事件


將事件處理常式繫結到「scroll」事件,或在元素上觸發該事件。

.on( "scroll" [, eventData ], handler )傳回:jQuery

說明:將事件處理常式繫結到「scroll」事件。

此頁面說明 scroll 事件。對於已棄用的 .scroll() 方法,請參閱 .scroll()

當使用者捲動至元素中不同位置時,scroll 事件會傳送至元素。它適用於 window 物件,也適用於可捲動的框架和已將 overflow CSS 屬性設定為 scroll 的元素(或在元素的明確高度或寬度小於其內容的高度或寬度時設定為 auto)。

例如,考慮下列 HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div id="target" style="overflow: scroll; width: 200px; height: 100px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
</div>
<div id="other">
Trigger the handler
</div>
<div id="log"></div>

樣式定義會讓目標元素變得很小,以利於捲動

圖 1 - 呈現的 HTML 說明

scroll 事件處理常式可以繫結至這個元素

1
2
3
$( "#target" ).on( "scroll", function() {
$( "#log" ).append( "<div>Handler for `scroll` called.</div>" );
} );

現在,當使用者向上或向下捲動文字時,會將一則或多則訊息附加至 <div id="log"></div>

已呼叫 `scroll` 處理常式。

若要手動觸發事件,請使用 .trigger( "scroll" )

1
2
3
$( "#other" ).on( "click", function() {
$( "#target" ).trigger( "scroll" );
} );

此程式碼執行後,按一下 觸發處理常式 也會附加訊息。

無論原因為何,只要元素的捲動位置變更,就會傳送 scroll 事件。滑鼠按一下或拖曳捲軸列、在元素內拖曳、按下箭頭鍵,或使用滑鼠的滾輪都可能造成此事件。

範例

在捲動頁面時執行某些動作

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
div {
color: blue;
}
p {
color: green;
}
span {
color: red;
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div>Try scrolling the iframe.</div>
<p>Paragraph - <span>Scroll happened!</span></p>
<script>
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( window ).on( "scroll", function() {
$( "span" ).css( "display", "inline" ).fadeOut( "slow" );
} );
</script>
</body>
</html>

示範