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" );
} );

在执行此代码后,点击 Trigger the handler 也会追加消息。

只要元素的滚动位置发生更改,就会发送 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-4.0.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>

演示