Rom*_*man 7 javascript scroll event-handling dom-events
当我滚动到某个元素时,我试图删除滚动事件侦听器。我想要做的是当某些元素在视口中时调用单击事件。问题是点击事件一直在调用,或者在第一次调用之后根本没有调用。(对不起 - 难以解释)我想删除滚动事件以停止调用点击函数。
我的代码:
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}%)`;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 16
您只能删除外部函数上的事件侦听器。您不能像以前使用的那样删除匿名函数上的事件侦听器。
替换此代码
window.addEventListener('scroll', () => { ... };
Run Code Online (Sandbox Code Playgroud)
而是这样做
window.addEventListener('scroll', someFunction);
Run Code Online (Sandbox Code Playgroud)
然后将您的功能逻辑移动到功能中
function someFunction() {
// add logic here
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在满足某些条件时删除点击侦听器,即当元素在视口中时
window.removeEventListener('scroll', someFunction);
Run Code Online (Sandbox Code Playgroud)
您应该尝试使用Intersection Observer (IO),而不是监听滚动事件。监听滚动事件并计算每个滚动上元素的位置可能会降低性能。使用 IO,只要页面上的两个元素彼此相交或与视口相交,您就可以使用回调函数。
要使用 IO,首先必须指定 IO 的选项。由于您想检查您的元素是否在视图中,因此请将该root元素排除在外。
let options = {
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
Run Code Online (Sandbox Code Playgroud)
然后指定要观看的元素:
let target = slideMenu; //document.querySelector('#oneElement') or document.querySelectorAll('.multiple-elements')
observer.observe(target); // if you have multiple elements, loop through them to add observer
Run Code Online (Sandbox Code Playgroud)
最后,您必须定义元素位于视口中后应该发生的情况:
let callback = (entries, observer) => {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// target element:
});
};
Run Code Online (Sandbox Code Playgroud)
如果您不再需要观察者,也可以取消观察某个元素。
检查w3c 的这个 polyfill以支持旧版浏览器。