我滚动到某个元素时,我试图删除滚动事件监听器。我想要做的是当一些元素在视口中时调用click事件。问题是,click事件始终保持呼叫,或者在第一次呼叫之后根本不保持呼叫。 (对不起 - 很难解释)我想删除滚动事件以停止调用点击功能。
我的代码:
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
}
然后,当满足某些条件时,即元素位于视口中时,您可以删除单击侦听器
window.removeEventListener('scroll', someFunction);