javascript - 如何删除滚动事件监听器?

标签 javascript scroll event-handling dom-events

当我滚动到某个元素时,我试图删除滚动事件监听器。我想做的是当某些元素位于视口(viewport)中时调用单击事件。问题是点击事件一直在调用,或者在第一次调用后根本不调用。 (抱歉 - 很难解释)我想删除滚动事件以停止调用单击函数。

我的代码:

   window.addEventListener('scroll', () => {
   window.onscroll = slideMenu;

        // offsetTop - the distance of the current element relative to the top;
        if (window.scrollY > elementTarget.offsetTop) {
            const scrolledPx = (window.scrollY - elementTarget.offsetTop);

            // going forward one step
            if (scrolledPx < viewportHeight) {
                // console.log('section one');
                const link = document.getElementById('2');
                if (link.stopclik === undefined) {
                    link.click();
                    link.stopclik = true;
                }
            }

            // SECOND STEP
            if (viewportHeight < scrolledPx && (viewportHeight * 2) > scrolledPx) {
                console.log('section two');

                // Initial state
                let scrollPos = 0;
                window.addEventListener('scroll', () => {
                    if ((document.body.getBoundingClientRect()).top > scrollPos) { // UP
                        const link1 = document.getElementById('1');
                        link1.stopclik = undefined;
                        if (link1.stopclik === undefined) {
                            link1.click();
                            link1.stopclik = true;
                        }
                    } else {
                        console.log('down');
                    }
                    // saves the new position for iteration.
                    scrollPos = (document.body.getBoundingClientRect()).top;
                });
            }

            if ((viewportHeight * 2) < scrolledPx && (viewportHeight * 3) > scrolledPx) {
                console.log('section three');
            }

            const moveInPercent = scrolledPx / base;
            const move = -1 * (moveInPercent);

            innerWrapper.style.transform = `translate(${move}%)`;
        }
    });

最佳答案

您只能删除外部函数上的事件监听器。您无法像您使用的那样删除匿名函数上的事件监听器。

替换此代码

window.addEventListener('scroll', () => { ... };

然后这样做

window.addEventListener('scroll', someFunction);

然后将您的函数逻辑移至函数中

function someFunction() {
  // add logic here
}

当满足某些条件时,即当元素位于视口(viewport)中时,您可以删除点击监听器

window.removeEventListener('scroll', someFunction);

关于javascript - 如何删除滚动事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254762/

相关文章:

javascript - 为什么使用脚本加载到 div 中的 html 不调用 javascript?

javascript - jQuery UI 对话框 - 无法删除按钮

javascript - 使用 MediaDevices.enumerateDevices() 观察变化

cocoa - 滚动 NSTextView 使滚动条处于错误位置

html - 在 react 中添加范围的 mouseup 事件

javascript - 为什么不同的灯箱链接打开的内容总是相同?

HTML 水平图像滚动不起作用

javascript - HostListener 使页面滚动无响应

Java - 接口(interface)事件处理 - 解析

java - GXT 3 : GridSelectionModel SelectionEvent/SelectionChangedEvent not firing