debounce函数意味着鼠标滚轮上的e.c preventdefault不再工作

debounce function means e.preventDefault on mousewheel no longer working

本文关键字:preventdefault 不再 工作 意味着 函数 鼠标 debounce      更新时间:2023-09-26

我正在使用鼠标滚轮改变页面的背景。我只想触发鼠标滚轮事件一次1000ms,因此我使用debounce函数。

在我添加debounce功能并使用e.preventDefault()之前,它阻止了滚动的工作。然而,现在我已经添加了debounce功能,这不再起作用,用户可以再次滚动页面。

请参阅下面的代码。

$(document).ready(function() {
    $(document).on('mousewheel DOMMouseScroll',debounce(function(e){
        e.preventDefault();
        //code to change the background image
    }, 1000))
});
function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };

然后像这样构建:

$(document).ready(function() {
    var changeBackground = debounce(function(e){
        //code to change the background image
    }, 1000)
    $(document).on('mousewheel DOMMouseScroll',debounce(function(e){
        e.preventDefault();
        changeBackground(e);
    })
});