如何在Chrome中启用鼠标滚轮?

问题描述 投票:0回答:1

当我将页面滚动到特殊块时,我使用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个回答
0
投票

堆叠一个侦听器以使先前的侦听器无效是棘手的,因为它们以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);
© www.soinside.com 2019 - 2024. All rights reserved.