gpt4 book ai didi

JavaScript:删除事件监听器不起作用

转载 作者:行者123 更新时间:2023-12-01 01:18:02 25 4
gpt4 key购买 nike

我想使用 JavaScript 删除事件监听器,但它似乎不起作用...我尝试将 debounce 以及 showPopup 函数作为参数传递给 removeEventListener.

const elementToListenForScroll = document.querySelector('.howitworks__mainheading');
const distanceToTop = elementToListenForScroll.getBoundingClientRect().top;

function debounce(func, wait = 20, immediate = true) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

function showPopup() {
const currentScrollPosition = window.scrollY;
if (currentScrollPosition > distanceToTop) {
console.log('hey it works');
window.removeEventListener('scroll', debounce);
}
}

window.addEventListener('scroll', debounce(showPopup));

最佳答案

debounce(showPopup)debounce 不同。

debounce(showPopup) 调用在 debounce 仅引用该函数时执行代码。

为了能够removeEventListener,您需要传递与传递给addEventListener相同的函数引用。

debounce(showPopup) 分配给某个变量并将其用于事件订阅/取消订阅。

示例:

    const elementToListenForScroll = 
document.querySelector('.howitworks__mainheading');
const distanceToTop = elementToListenForScroll.getBoundingClientRect().top;


var realReference = debounce(showPopup);
function debounce(func, wait = 20, immediate = true) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

function showPopup() {
const currentScrollPosition = window.scrollY;
if(currentScrollPosition > distanceToTop) {
console.log('hey it works');
window.removeEventListener('scroll', realReference);
}
}

window.addEventListener('scroll', realReference);

关于JavaScript:删除事件监听器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com