【问题标题】:How to enable mousewheel in chrome?如何在chrome中启用鼠标滚轮?
【发布时间】:2020-05-07 07:18:50
【问题描述】:

当我将页面滚动到特殊块时,我使用 javascript 禁用鼠标滚轮。 我使用了很多方法,但它们都在 Firefox 中工作,而不是在 chrome 中。 对于 chrome,我找到了一种带有 preventDefault 的特殊方法。 但我不知道如何启用它们。 这是代码:

const options = {
    rootMargin: "-400px"
};

const observer = new IntersectionObserver(function (entries, observer) {
    entries.forEach(entry => {
        console.log(entry.isIntersecting);
        if (entry.isIntersecting === true) {
            document.querySelector('body').classList.add('fixed');
            document.body.addEventListener('wheel', function (e) {
                e.preventDefault();
            }, {passive: false});

            $('html, body').animate({
                scrollTop: scrollCenter
            }, 1000);

            setTimeout(function () {
                document.querySelector('body').classList.remove('fixed');
                document.body.addEventListener('wheel', function (e) {
                    // override prevented flag to prevent jquery from discarding event
                    e.isDefaultPrevented = function () {
                        return false;
                    }
                });
            }, 1000);

        }
    });
}, options);

observer.observe(produtsBlock);

感谢您的帮助。

【问题讨论】:

    标签: javascript mousewheel preventdefault


    【解决方案1】:

    堆叠一个侦听器以使先前的侦听器无效是很棘手的,因为它们是按 FIFO 顺序触发的。

    一些选项:

    1。移除监听器

    您可以在这段时间之后移除阻塞监听器。

    使用命名函数:

    
    const prevent = (e) => e.preventDefault();
    document.body.addEventListener('wheel', prevent, { passive: false });
    
    

    您可以在之后删除它:

    
    setTimeout(function () {
      document.querySelector('body').classList.remove('fixed');
      document.body.removeEventListener('wheel', prevent);
    }, 1000);
    
    

    2。使用标志

    使用状态标志来处理preventDefault

    const state = { prevent: true };
    
    const prevent = (e) => {
      if (state.prevent) {
        e.preventDefault();
      }
    };
    
    document.body.addEventListener("wheel", prevent, { passive: false });
    

    然后改变标志:

    setTimeout(function () {
      document.querySelector("body").classList.remove("fixed");
      state.prevent = false;
    }, 1000);
    

    【讨论】:

    • 请不要忘记勾选这个作为选择的答案,所以它被标记为已回答。谢谢@serii :)
    • 非常感谢,但我不明白,如何选择你的答案?
    • 您可以对问题进行投票并接受。本文解释了这些概念:What should I do when someone answers my question? 希望对您有所帮助:)
    • 抱歉,但我认为,我没有投票或接受答案的特权。我没有看到 so 选项。
    • 我的声望为 11,但必须为 15 才能接受和投票))
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多