首页 > 解决方案 > 如何使用 removeEventListener 停止 EventListener

问题描述

我想在事件执行后停止监听事件。我找不到事件侦听器仍在侦听的原因。

    const scrollMe = document.querySelector('.scroll-me');
    const imgMaximmo = document.querySelector('.maximmo');
    
  
     scrollingTo = () =>{
        window.scrollTo(0,850);
         }

    cover.addEventListener('wheel', ()=>{
            cover.style.height = '105vh';
            cover.style.position = 'relative';
            cover.style.marginTop ='-52px';
            imgMaximmo.style.marginTop ='2%';
            scrollingTo(); 

    })
       cover.removeEventListener('wheel', scrollingTo, { capture: false });```

标签: javascriptdom

解决方案


你使用removeEventListener不正确。此方法接受方法中使用的相同函数addEventListener。您使用匿名函数订阅了事件,但尝试使用不同的函数取消订阅。因此,您必须将您的事件处理函数设置为某个常量,然后使用它来订阅和取消订阅该事件。尝试像这样更改您的代码:

const scrollMe = document.querySelector('.scroll-me');
const imgMaximmo = document.querySelector('.maximmo');

// Function used inside handler
const scrollingTo = () =>{
  window.scrollTo(0,850);
}

// Handler must be set into named function to add and remove it
const wheelEventHandler = () => {
  cover.style.height = '105vh';
  cover.style.position = 'relative';
  cover.style.marginTop ='-52px';
  imgMaximmo.style.marginTop ='2%';
  scrollingTo(); 
}

// Subscribe to the event using event handler function
cover.addEventListener('wheel', wheelEventHandler);

// Unsubscribe from event using the same function
cover.removeEventListener('wheel', wheelEventHandler);

推荐阅读