【问题标题】:Prevent mouse wheel scrolling, but not scrollbar event. JavaScript防止鼠标滚轮滚动,但不是滚动条事件。 JavaScript
【发布时间】:2013-11-30 08:19:28
【问题描述】:

我需要使网页只能通过滚动条滚动。我试图找到如何捕捉滚动条事件,但我认为这是不可能的。目前我使用这个功能:

function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}
function wheel(e) {
    preventDefault(e);
}
function disable_scroll() {
    if (window.addEventListener) {
        window.addEventListener('DOMMouseScroll', wheel, false);
    }
    window.onmousewheel = document.onmousewheel = wheel;
}

但它们在我的情况下并不是很有用,因为它们会阻止所有滚动事件。你有什么想法?我已经考虑了 3 天,但我没有找到任何答案(还有问题)。谢谢!

【问题讨论】:

  • 我只是将你的函数放在我的控制台中,它似乎工作正常。我可以单击并拖动滚动条,但鼠标滚轮不起作用。这就是你想要的吗?

标签: javascript html browser scroll


【解决方案1】:

防止用鼠标滚轮滚动窗口。

// Old Method
window.onwheel = function(){ return false; }

编辑(2020 年 1 月):@MatthewMorrone 告知上述代码以在窗口上绑定车轮事件,window.document 和 window.document.body (标记为'旧方法')不再起作用。更多细节 请查收:https://www.chromestatus.com/features/6662647093133312

由于文档级别的Wheel/Mousewheel 事件监听器是treated as Passive,我们需要将此事件监听器标记为Active。请检查以下代码以获取解决方案。更多信息:https://developers.google.com/web/updates/2019/02/scrolling-intervention

// New Working Method
window.addEventListener("wheel", e => e.preventDefault(), { passive:false })

如果<div>或其他元素的内容是可滚动的,你可以这样阻止它:

document.getElementById('{element-id}').onwheel = function(){ return false; }

干杯...

【讨论】:

  • 这似乎不再起作用,在控制台中得到这个:[干预] 由于目标被视为被动,因此无法在被动事件侦听器中阻止默认值。见chromestatus.com/features/6662647093133312
  • @MatthewMorrone 感谢您指出这一点。请检查解决方案的更新答案。
【解决方案2】:

使用鼠标滚轮防止窗口滚动的jQuery解决方案:

$(window).bind('mousewheel DOMMouseScroll', function(event){ return false});

如果您想防止在单个 DOM 元素中使用鼠标滚轮滚动,请尝试以下操作:

$('#{element-id}').bind('mousewheel DOMMouseScroll', function (e) { return false; });

DOMMouseScroll 事件在 Firefox 中使用,因此您必须同时监听。

【讨论】:

  • 工作就像一个魅力!
  • 它实际上在 Chrome 上运行良好,从版本 78.0.3904.108 开始
【解决方案3】:

我目前正在使用它,它工作正常。使用栏滚动可以正常工作,但鼠标滚轮不起作用。

我这样做的原因是我有自定义代码来滚动我想要的方式,但如果不添加任何代码它就不会滚动滚轮。

window.addEventListener('wheel', function(e) {  
    e.preventDefault();
    // add custom scroll code if you want
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2012-02-14
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    相关资源
    最近更新 更多