.scroll()

.scroll( handler )返回类型:jQuery

描述:把事件处理函数绑定到“scroll”JavaScript事件上,或者在元素上触发此事件。

此方法在前两种变体中是.on( "scroll", handler )的简写,在第三种变体中是.trigger( "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" ).scroll(function() {
$( "#log" ).append( "<div>Handler for .scroll() called.</div>" );
});

现在,当用户将文本滚上滚下时,一个或更多的消息会追加到<div id="log"></div>

Handler for .scroll() called.

若要手工触发事件,请不带参数地应用.scroll()

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

代码执行之后,在Trigger the handler上点击,将追加此消息。

每当元素的滚动位置改变时,就发送scroll事件,无论何种情况。鼠标点击或拖曳滚动条,在元素内部拖曳,按下方向键,或者使用鼠标的滚侏罗纪都能导致此事件。

补充说明:

  • 因为.scroll()方法是.on( "scroll", handler )的简写,所以可以使用.off( "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>scroll demo</title>
<style>
div {
color: blue;
}
p {
color: green;
}
span {
color: red;
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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 ).scroll(function() {
$( "span" ).css( "display", "inline" ).fadeOut( "slow" );
});
</script>
</body>
</html>

演示: