如何使事件侦听器功能'mouse wheel'响应速度降低?



我想创建一个效果,当鼠标上的滚轮移动时,页面的图像和颜色会发生变化。我已经做到了这一点,但我现在面临的问题是效果几乎是瞬间的,只是轮子最轻微的移动和事件被触发。

如何使鼠标滚轮事件的响应速度降低(渐进(,就像这里一样(效果有点流行,抱歉我可以找到更好的例子(。提前感谢您的帮助。对于解释不佳或琐碎的问题,提前道歉。

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 将确保函数每秒最多运行 X 次,无论调用多少次。

http://underscorejs.org/#debounce

http://underscorejs.org/#throttle

最新更新