當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery .scroll()用法及代碼示例

用法
.scroll( handler ) => jQuery

說明:將事件處理程序綁定到 "scroll" JavaScript 事件,或在元素上觸發該事件。

  • 添加的版本:1.0.scroll( handler )

    • handler
      類型:Function(Event eventObject)
      每次觸發事件時執行的函數。
  • 添加的版本:1.4.3.scroll( [eventData ], handler )

    • eventData
      類型:Anything
      包含將傳遞給事件處理程序的數據的對象。
    • handler
      類型:Function(Event eventObject)
      每次觸發事件時執行的函數。
  • 添加的版本:1.0.scroll()

    • 此簽名不接受任何參數。

此方法是第一和第二變體中.on( "scroll", handler ) 和第三變體中.trigger( "scroll" ) 的快捷方式。

當用戶滾動到元素中的不同位置時,scroll 事件被發送到元素。它適用於window 對象,也適用於overflow CSS 屬性設置為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>

樣式定義的存在是為了使目標元素小到可以滾動:

圖 1 - 呈現的 HTML 的插圖

scroll 事件處理程序可以綁定到此元素:

$( "#target" ).scroll(function() {
  $( "#log" ).append( "<div>Handler for .scroll() called.</div>" );
});

現在,當用戶向上或向下滾動文本時,一條或多條消息會附加到 <div id="log"></div>

.scroll() 的處理程序被調用。

要手動觸發事件,請應用不帶參數的.scroll()

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

這段代碼執行後,點擊觸發處理程序還將附加消息。

每當元素的滾動位置發生變化時,無論原因如何,都會發送 scroll 事件。在滾動條上單擊或拖動鼠標、在元素內拖動、按箭頭鍵或使用鼠標滾輪都可能導致此事件。

其他注意事項:

  • 由於 .scroll() 方法隻是 .on( "scroll", handler ) 的簡寫,因此可以使用 .off( "scroll" ) 進行分離。

例子:

滾動頁麵時執行以下操作:

<!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-3.5.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 ).scroll(function() {
  $( "span" ).css( "display", "inline" ).fadeOut( "slow" );
});
</script>
 
</body>
</html>

演示:

相關用法


注:本文由純淨天空篩選整理自jquery.com大神的英文原創作品 .scroll()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。