概述 .scroll( handler(eventObject) )
返回值:jQuery
描述:为 JavaScript 的 "scroll" 事件绑定一个处理函数,或者触发元素上的该事件。
这个函数的前两个用法是 .bind('scroll', handler)
的快捷方式,第3个不带参数的用法是 .trigger('scroll')
的快捷方式。
当用户在元素内执行了滚动操作,就会在这个元素上触发scroll
事件。它适用于window
对象,但也可以是可滚动frames与CSS overflow
属性设置为scroll
的元素(或auto
时,元素的显示高度小于其内容高度)。
举例来说,请看下面的HTML:
- <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>
通过样式定义,使目标元素足够小以至它可以滚动:
scroll
事件处理函数可以绑定到这个元素:
- $('#target').scroll(function() {
- $('#log').append('<div>Handler for .scroll() called.</div>');
- });
现在,当用户向上或向下滚动文本时,从而向 <div id="log"></div>
中追加了如下信息::
Handler for .scroll() called.
我们可以调用不带参数的 .scroll()
方法,手动触发这个事件:
- $('#other').click(function() {
- $('#target').scroll();
- });
这些代码执行后,点击 Trigger the handler 同样警报显示。
每当元素的滚动位置的变化时,该元素就会触发scroll
事件,不管什么原因。鼠标点击或拖动滚动条,拖动里面的元素,按箭头键,或使用鼠标的滚轮都可能导致触发此事件。
.select()
方法只是作为.on( "select", handler )
的一个速记写法,移除该事件可以使用.off(
"select"
)
。
示例
在页面滚动时触发一系列动作:
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- div { color:blue; }
- p { color:green; }
- span { color:red; display:none; }
- </style>
- <script src="http://code.jquery.com/jquery-latest.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>