debounce function means e.preventDefault on mousewheel no longer working

时光怂恿深爱的人放手 提交于 2019-12-11 04:24:35

问题


I am chaging the background of the page using mousewheel. I only want to trigger the mousewheel event once 1000ms, so for that I am using a debounce function.

Before I added the debounce function and used e.preventDefault() it prevented the scroll from working. However, now that I have added the debounce function this no longer works and the user can scroll the page again.

Please see code below.

$(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);
  };

回答1:


then build it like this:

$(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);
    })
});


来源:https://stackoverflow.com/questions/39237942/debounce-function-means-e-preventdefault-on-mousewheel-no-longer-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!