javascript - 如何使 'mouse wheel' 事件监听器函数响应较慢?

标签 javascript jquery html css

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

如何使鼠标滚轮事件的响应性(逐渐)降低为 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%)"
        });

    }
}

最佳答案

您可能正在寻找debouncethrottle 方法。

Debounce 将确保您的代码仅在一组调用结束时运行一次,即使函数被多次调用也是如此。

Throttle 将确保一个函数每秒最多运行 X 次,而不管它被调用了多少次。

http://underscorejs.org/#debounce

http://underscorejs.org/#throttle

关于javascript - 如何使 'mouse wheel' 事件监听器函数响应较慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222364/

相关文章:

html - flexbox 在顶部显示子 div

PHP 套接字 - 我需要什么来使用它们?

javascript - 在 VueJS 中用相同的组件包装三个特定的路由

JavaScript/Jquery : How to find line-through words

javascript - Highcharts 列 : add dynamically series with drilldown data

javascript - javascript 数据库操作的对象方法中的异步回调

html - div居中但也固定

javascript - 如何在动态表的特定列中插入/更新项目?

javascript - 类型错误 : object is not a function when defining models in NodeJs using Sequelize

jquery - 如何停止 jQuery SlideToggle 溜溜球?