.scroll()

.scroll( handler(eventObject) ) 官网原E文: jQuery

描述: 为 "scroll" 事件绑定一个处理函数,或者触发元素上的 "scroll" 事件。

  • version added: 1.0.scroll( handler(eventObject) )

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.4.3.scroll( [ eventData ], handler(eventObject) )

    eventData将要传递给事件处理函数的数据映射。

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.0.scroll()

这个函数的第一种用法是 .bind('scroll', handler) 的快捷方式,第二种用法是 .trigger('scroll') 的快捷方式。

当用户滚动元素中到一个不同的地方时,scroll事件将发送到这个元素。它适用于window对象,但也可滚动框架与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.

当不同的元素被点击时我们也可以触发这个事件:

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

这些代码执行后,点击 Trigger the handler 同样警报显示。

每当元素的滚动位置的变化时scroll事件就会被发送该元素,不管什么原因。鼠标点击或拖动滚动条,拖动里面的元素,按箭头键,或使用鼠标的滚轮都可能导致触发此事件。

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>

Demo:

jQuery 1.6 API 中文版Clove整理、修订