我有一个从鼠标滚轮滚动开始的功能,但是,如果我进行了更长的滚动,它将执行2-3次。所以我必须找到一种方法来阻止它运行,如果它在2秒内被调用了1次以上。有任何想法吗?
PS:这是我的功能。如果您知道一种更好的滚动方式来启动它,而不考虑滚动时间有多长,我也将不胜感激。
if (window.addEventListener) {
// IE9, Chrome, Safari, Opera
window.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
window.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
var s = 0;
function MouseWheelHandler(e) {
// cross-browser wheel delta
var e = window.event || e; // old IE support
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
e.preventDefault();
...
}
更新:根据我在注释和答案中读到的想法,我制定了自己的代码版本。就是这个 :
function MouseWheelHandler(e) {
var e = window.event || e;
// cross-browser wheel delta
// old IE support
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
e.preventDefault();
GoUpDown(delta,e);
}
function GoUpDown(delta,e) {
if(timer ==0){ timer =1;
setTimeout(function () {timer =0;},4200);
/*function stuff*/
}
最佳答案
根据Morten OC的反跳代码修改的节流方式
http://jsfiddle.net/43sgpme7/13/
var interval = 2000;
var count = 0;
function action() {
count++;
$("p").html(new Date().getTime() + "-" + count)
}
$(".scroll").scroll(function () {
var self = this;
if (this.lastScroll === undefined) {
this.lastScroll = Date.now() - interval;
}
/*calculate how long until next execution should happen*/
var nextTime = interval - Date.now() + this.lastScroll;
/*it doesn't make sense that time range is smaller than 0*/
if (nextTime < 0) {
nextTime = 0;
}
if (this.scrollTo) clearTimeout(this.scrollTo);
this.scrollTo = setTimeout(function () {
self.lastScroll = Date.now();
action();
}, nextTime);
});