.scroll()
.scroll( handler(eventObject) ) 返回: jQuery
描述: 為 "scroll" 事件綁定一個處理函數(shù),或者觸發(fā)元素上的 "scroll" 事件。
-
version added: 1.0.scroll( handler(eventObject) )
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數(shù)。
-
version added: 1.4.3.scroll( [ eventData ], handler(eventObject) )
eventData將要傳遞給事件處理函數(shù)的數(shù)據(jù)映射。
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數(shù)。
version added: 1.0.scroll()
這個函數(shù)的第一種用法是 .bind('scroll', handler) 的快捷方式,第二種用法是 .trigger('scroll') 的快捷方式。
當用戶滾動元素中到一個不同的地方時,scroll事件將發(fā)送到這個元素。它適用于window對象,但也可滾動框架與CSS overflow屬性設置為scroll的元素(或auto時,元素的顯示高度小于其內(nèi)容高度)。
舉例來說,請看下面的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事件處理函數(shù)可以綁定到這個元素:
$('#target').scroll(function() {
$('#log').append('<div>Handler for .scroll() called.</div>');
});
現(xiàn)在,當用戶向上或向下滾動文本時,一個或多個消息追加到<div id="log"></div> :
Handler for .scroll() called.
當不同的元素被點擊時我們也可以觸發(fā)這個事件:
$('#other').click(function() {
$('#target').scroll();
});
這些代碼執(zhí)行后,點擊 Trigger the handler 同樣警報顯示。
每當元素的滾動位置的變化時scroll事件就會被發(fā)送該元素,不管什么原因。鼠標點擊或拖動滾動條,拖動里面的元素,按箭頭鍵,或使用鼠標的滾輪都可能導致觸發(fā)此事件。
Example:
To do something when your page is scrolled:
<!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.min.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>