我想使用 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/