gpt4 book ai didi

javascript - 如何在第一次结束前停止第二次事件鼠标滚轮

转载 作者:行者123 更新时间:2023-11-30 09:36:30 25 4
gpt4 key购买 nike

我有代码可以让我的窗口从一个元素滚动到另一个元素。如果我稍微滚动一下鼠标滚轮,它就会正常工作。但是,如果我滚动得更快,就会遇到麻烦。

var currentPosition = 1;
angular.element(document).on("mousewheel DOMMouseScroll", function (e) {
e.preventDefault();
e.stopPropagation();

var isUp = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? true : false;

if (isUp) {
if (currentPosition > 0) {
currentPosition--;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]);
}
}
else {
if (currentPosition < 3) {
currentPosition++;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]);
}
}
});

回答

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

if (immediate && !timeout) {
func.apply(context, args);
}
};
}

最佳答案

这个问题叫做去抖动,如果你用谷歌搜索,你可能会发现它有很多不同的版本。基本上,当用户向下滚动页面时,twitter 已经注意到,无限滚动脚本正在加载更多内容。但随后他们注意到,当您足够快地执行脚本时,脚本会多次触发,并导致内存泄漏和页面无响应。所以他们想出了这个主意,去抖动。简单地说,您在运行原始事件之前在函数中添加一个计时器,如果计时器仍然存在,则取消您的事件。所以当你向下滚动而不是触发 onscroll 事件 20 次时,超时,它会每 x 毫秒触发 N 次。

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

if (immediate && !self.timeout) {
func.apply(context, args);
}
};
}

然后在你原来的事件监听器中,

    angular.element(document).on("mousewheel DOMMouseScroll", debounce(function(e){
e.preventDefault();
e.stopPropagation();

var isUp = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? true : false;

if (isUp) {
if (currentPosition > 0) {
currentPosition--;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]);
}
}
else {
if (currentPosition < 3) {
currentPosition++;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]);
}
}
});
}, 300));

关于javascript - 如何在第一次结束前停止第二次事件鼠标滚轮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43236263/

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