如何禁用addEventListener与鼠标滚轮事件



我正在创建一个水平滚动网站,想知道当光标指针位于元素内时,我是否可以禁用addEventListener

下面是一个例子。

<div class="bar">Disable mousewheel event when the cursor pointer is within this div</div>
<script>
window.addEventListener("mousewheel", (e) => {
if (e.deltaX === 0) {
e.stopPropagation();
e.preventDefault();
window.scrollBy(e.deltaY, 0);
}
});
</script>

关键不在于"禁用">"删除">事件侦听器…

关键是知道鼠标是否在一个特定的元素上,以便做其他事情…
(实际上,什么都不做应该被认为是"其他事情")。

let barFlag = false;
window.addEventListener("mousewheel", (e) => {
if(!barFlag){
console.log("mousewheel!")
}else{
console.log("No!")
}
});
document.querySelectorAll(".bar").forEach(function(bar){
bar.addEventListener("mouseenter", function(){
barFlag = true;
});
bar.addEventListener("mouseleave", function(){
barFlag = false;
})
})
.spacer{
height: 500px;
}
.bar{
height: 300px;
border: 1px solid red;
}
<div class="spacer"></div>
<div class="bar">Disable mousewheel event when the cursor pointer is within this div</div>
<div class="spacer"></div>
<div class="bar">Disable mousewheel event here too</div>
<div class="spacer"></div>

最新更新