在 jQuery 中可以使用 scrollTop() 方法来确定滚动事件的方向, scrollTop() 方法用于设置或返回所选元素的垂直滚动条位置. 利用这种方法, 我们就可以确定滚动方向.
语法:
$(selector).scrollTop(position)
参数: 此方法接受单个参数 position, 该 position 参数是可选的. 它用于指定垂直滚动条位置 (以像素为单位).
返回值: 返回所选元素滚动条的垂直位置.
示例:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8">
- <style>
- HTML,body { height: 300% } div { position: fixed; padding-left: 10px;
- padding-top: 30px; height: 10%; width: 35%; font-weight: bold; border:
- 2px solid red; }
- </style>
- </head>
- <body>
- <div>
- </div>
- <script src="https://code.jquery.com/jquery-1.10.2.js">
- </script>
- <script>
- var position = $(Windows).scrollTop();
- $(Windows).scroll(function() {
- var scroll = $(Windows).scrollTop();
- if (scroll > position) {
- console.log('scrollDown');
- $('div').text('向下滚动');
- } else {
- console.log('scrollUp');
- $('div').text('向上滚动');
- }
- position = scroll;
- });
- </script>
- </body>
- </HTML>
效果图:
来源: http://www.css88.com/qa/jquery/10478.html