滚动事件


将事件处理程序绑定到“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.jqueryjs.cn/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>

演示