jquery.mousewheel.js鼠标滚动监听插件

2021-09-11  本文已影响0人  MC桥默

前言

项目中,有时需要监听鼠标的滚动事件,根据鼠标的滚动方向做出相应的事件处理,此时我们可以使用jquery.mousewheel.js插件。
jquery.mousewheel.js插件基于jquery的支持,使用前需要引入jquery。

使用方法

需要把 mousewheel 事件绑定到一个元素上即可。当然也可以使用类似 jQuery 中其他的事件方法写法。

// 方式1:using on
$('#某个元素').on('mousewheel', function(event) {
    console.log(event.deltaX, event.deltaY, event.deltaFactor);
});

// 方式2:using the event helper
$('#某个元素').mousewheel(function(event) {
    console.log(event.deltaX, event.deltaY, event.deltaFactor);
});

// 方式3:如果想要对整个窗口进行滚轮事件监听,可以将监听添加在 window 上。
$(window).mousewheel(function(event) {
     console.log(event.deltaX, event.deltaY, event.deltaFactor);
});
属性值

deltaX:值为负的(-1),则表示滚轮向左滚动。值为正的(1),则表示滚轮向右滚动。
deltaY:值为负的(-1),则表示滚轮向下滚动。值为正的(1),则表示滚轮向上滚动。
deltaFactor:增量因子。通过 deltaFactor * deltaX 或者 deltaFactor * deltaY 可以得到浏览器实际的滚动距离。

示例代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery-mousewheel</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="jquery-mousewheel.js"></script>
        <style></style>
    </head>
    <body>
        <div id="cube"></div>
    </body>
    <script>
        $(function() {
                $(window).mousewheel(function(event) {
                    //输出滚轮事件响应结果
                    console.log(event.deltaX, event.deltaY, event.deltaFactor);
                });
              });
    </script>
</html>

上一篇 下一篇

猜你喜欢

热点阅读