js 实现鼠标划入滚动区域;滚轮就可以滚动

js 实现鼠标划入滚动区域;滚轮就可以滚动

阅读 3.8k
2 个回答

============更新

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>scroll control</title>
    <style>
        #content{
            width: 400px;
            height: 2000px;
        }
        #scroll-control{
            width: 400px;
            height: 400px;
            position: fixed;
            top: 30px;
            right: 30px;
            background-color: #080;
        }
    </style>
</head>
<body>
    <h1>禁用滚动</h1>
    <p id="content">
        <a href="https://github.com/jacktown11/js-practice/tree/master/scroll_cancel">github源码</a>
    </p>
    <p id="scroll-control"></p>

    <script>
        let scrollCtr = {
            node: document.getElementById('scroll-control'),
            isScrollable: false,
            setEvent(){
                let self = this;
                document.onmousewheel = function(event){
                    console.log('mousescroll');
                    if(!self.isScrollable){
                        event.preventDefault();
                    }
                };
                this.node.onmouseover = function(event){
                    self.isScrollable = true;
                };
                this.node.onmouseleave = function(event){
                    self.isScrollable = false;
                }
            }
        };
        scrollCtr.setEvent();

    </script>
</body>
</html>

在线演示

============原答案

document上监听mousewheel/mousescroll事件,每次滚动时判断鼠标位置(可能通过事件触发是鼠标在页面的位置event.clientXevent.clientY来判断,或者给滚动区域绑定鼠标移入移出事件,记录鼠标是否处在滚动取悦),来决定是否调用event.preventDefault()取消滚动

新手上路,请多包涵

onmouseover在滚动区域内写这个事件 调用滚轮滚动方法。移除滚轮区域调用停止滚轮滚动方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题