1

マウスホイールを使用してページの背景を変更しています。マウスホイール イベントを 1000 ミリ秒に 1 回だけトリガーしたいので、そのためにデバウンス機能を使用しています。

デバウンス機能を追加して使用する前はe.preventDefault()、スクロールが機能しませんでした。ただし、デバウンス機能を追加したため、これは機能しなくなり、ユーザーはページを再度スクロールできます。

以下のコードを参照してください。

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

1 に答える 1

1

次に、次のようにビルドします。

$(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);
    })
});
于 2016-08-30T22:31:17.143 に答える