js阻止默认事件踩坑

2023-08-26 15:30:14 浏览数 (2)

人这种卑鄙的东西,什么都会习惯的。——陀思妥耶夫斯基《罪与罚》

今天遇到一个问题,我想阻止浏览器默认的滚动事件,却阻止不了还一直报错

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div style="height: 2000px;background:#888">

    </div>
    <script>
        document.addEventListener('wheel', e => {
            e.preventDefault()
        })
    </script>
</body>

</html>

此处在addEventListener中添加一个参数``{ passive: false }

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div style="height: 2000px;background:#888">

    </div>
    <script>
        document.addEventListener('wheel', e => {
            e.preventDefault()
        }, { passive: false })
    </script>
</body>

</html>

即可解决

0 人点赞