我正在尝试使用wheel
事件和节流函数创建我自己的简单的完全高度滚动脚本(因为我只希望每X毫秒注册一卷滚动。我希望将wheel
事件的事件数据传递到throttle()
函数正在节流的函数中。
下面是我的代码的简化版本:
function throttle(callback, limit) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait) { // If we're not waiting
callback.call(); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}
function onScroll(event) {
// do stuff here on scroll
}
window.addEventListener('wheel', throttle(onScroll, 700), false);
如果我不需要来自wheel
事件的数据,这会很好,但是我需要使用event.deltaY
来确定onScroll()
函数内部的滚动方向。
本质上,我希望将最后一行更改为以下内容(尽管我知道这是行不通的):
window.addEventListener('wheel', throttle(onScroll(event), 700), false);
所以.
如何将wheel
事件数据传递到onScroll()
函数中,同时仍在节流?
我尝试过的:
我尝试了下面的代码,这样我就可以将event
数据传递到throttle()
函数中,它成功地工作了
window.addEventListener('wheel', function(e) {
throttle(onScroll, 700, e)
}, false);
但是,我不知道如何处理我的e
函数中的throttle()
函数,以便能够将它传递给onScroll()
函数。我试着用:
callback.call(); // Execute users function
至:
callback.call(e); // Execute users function
(使用传递给油门函数的e
)
但这阻止了onScroll
函数被调用.(我假设是因为throttle()
返回了一个函数,但是这个返回的函数没有被调用,因为它包装在eventListener
中的另一个函数中?)
发布于 2019-03-14 14:01:40
只要把论点看一遍:
function throttle(callback, limit) {
var wait = false;
return function (...args) {
if (!wait) {
callback(...args);
wait = true;
setTimeout(function () {
wait = false;
}, limit);
}
}
}
https://stackoverflow.com/questions/55164410
复制相似问题