如何确定jQuery滚动事件的方向

如何确定jQuery滚动事件的方向

jQuery中的scrollTop()方法是用来设置或返回所选元素的垂直滚动条位置。在这个方法的帮助下,我们可以找到鼠标的滚动方向。语法。

$(selector).scrollTop(position)

参数:该方法接受单参数position,它是可选的。它用于指定垂直滚动条的位置,单位是像素。
返回值:它返回所选元素的滚动条的垂直位置。

例子:

<!DOCTYPE html>
<html>
 
<head>
    <title>
        Determine the direction of scroll event
    </title>
     
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
     
    <style>
        html, body {
            height: 300%
        }
         
        div {
            position: fixed;
            padding-left: 10px;
            padding-top: 30px;
            height: 10%;
            width: 35%;
            background: lightgrey;
            font-weight: bold;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
 
    <div></div>
     
    <!-- Script to determine the direction
    of a jQuery scroll event -->
    <script>
        var position = (window).scrollTop();
 
        (window).scroll(function() {
            var scroll = (window).scrollTop();
            if (scroll>position) {
                console.log('scrollDown');
                ('div').text('Scrolling Down Scripts');
            } else {
                console.log('scrollUp');
                $('div').text('Scrolling Up Scripts');
            }
            position = scroll;
        });
    </script>
</body>
 
</html>                   

输出:

  • 向上滚动:

如何确定jQuery滚动事件的方向

  • 向下滚动:

如何确定jQuery滚动事件的方向

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程