javascript - 如何使用 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 });```
解决方案
你使用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);
推荐阅读
- javascript - 在 Chrome Devtools 协议中,什么是 `injectedScriptId`?
- java - 如何使用 spring 'ResourcePatternResolver' 从指定路径读取所有文件
- django - Nginx 和 uwsgi 使用 Moviepy 花费 n* 加载时间
- javascript - 无法在导入的函数上运行模拟
- java - 如何为“TAB”和“ARROW”键自定义 NatTable 的表格单元格导航功能以获得可接受的可用性
- javascript - 如何使用尽可能少的代码使用引导程序制作多项目轮播?
- python - 无论我做什么都无法将数据附加到文件
- java - Maven 原型`quickstart` 无法扩展其 POM
- javascript - 提交表单数据并在新的弹出窗口中显示表单数据
- php - PHP:致命错误:未捕获的错误:调用未定义的方法 DB_Connect::storeClient()