我想创建一种效果,当鼠标滚轮移动时,页面的图像和颜色会发生变化。我已经实现了这一点,但我现在面临的问题是效果几乎是瞬间的,只需稍微移动一下轮子就会触发事件。
如何使鼠标滚轮事件的响应性(逐渐)降低为 here (效果有点大众化,不好意思找不到更好的例子了)。先谢谢您的帮助。对于糟糕的解释或微不足道的问题,提前致歉。
function mouseHandler(e) {
console.log(e.originalEvent.deltaY);
// This is where my problem is, I cannot think of another way besides this.
if (e.originalEvent.deltaY < 0) {
position = position === 0 ? pages.length - 1 : position - 1;
} else {
position = (position + 1) % pages.length;
}
$(".banner_image").fadeOut(0);
if (pages[position] === "../../public/images/Avatar.png") {
$("body").css("background-color", "#00a8ff");
$(".navigation-wrapper").css("background-color", "#00a8ff");
$(".banner").css({
position: "fixed",
top: "50%",
left: "25%",
transform: "(-50%, -50%)"
});
}
else if (pages[position] === "../../public/images/Burger.png") {
$("body").css("background-color", "#e84118");
$(".navigation-wrapper").css("background-color", "#e84118");
$(".banner").css({
position: "fixed",
top: "50%",
left: "25%",
transform: "(-50%, -50%)"
});
}
else if (pages[position] === "../../public/images/IceCream2.png") {
$("body").css("background-color", "#f1c40f");
$(".navigation-wrapper").css("background-color", "#f1c40f");
$(".banner").css({
position: "fixed",
top: "50%",
left: "25%",
transform: "(-50%, -50%)"
});
}
}
最佳答案
您可能正在寻找debounce 或throttle 方法。
Debounce 将确保您的代码仅在一组调用结束时运行一次,即使函数被多次调用也是如此。
Throttle 将确保一个函数每秒最多运行 X 次,而不管它被调用了多少次。
关于javascript - 如何使 'mouse wheel' 事件监听器函数响应较慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222364/