javascript - 事件处理程序被禁用的时间比预期的要长

标签 javascript events scroll

我正在制作一个简单的全视口(viewport)滚动器。您可以通过触发wheel事件来更改部分。

为了防止事件处理程序在行中多次触发并跳过页面,我添加了一个计时器,计算存储在变量中的 date.now()date.now 之间的差异() 在事件处理程序中。这种情况主要发生在您垃圾滚动时,它会让您必须等待大约 3 秒才能再次滚动,而不是 200 毫秒。如何防止这种情况发生?

document.ready = (fn) => {
  if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}


document.ready(() => {

  const SECTIONS = document.querySelectorAll('.section');  
  let current;
  let onWheelTimeout = 'poop';
  let time = Date.now()
  
    // initialize first section as active
    _.first(SECTIONS).classList.add('active');
    
    document.addEventListener('wheel', onWheel)



  
  function goSectionUp() {
    const current = document.querySelector('.active');
    current.classList.remove('active');

    if(current.previousElementSibling) {
      current.previousElementSibling.classList.add('active');
    } else {
      _.last(SECTIONS).classList.add('active');
    }
  }
  
  function goSectionDown() {
    const current = document.querySelector('.active');
    current.classList.remove('active');

    if(current.nextElementSibling) {
      current.nextElementSibling.classList.add('active');
    } else {
      _.first(SECTIONS).classList.add('active');
    }
  }



  function onWheel(e) {
    const now = Date.now()
    const diff = now - time;
    time = now;
    if(diff > 200) {
      if(e.deltaY < 0) {
        onScroll('up')
      } else {
        onScroll('down')
      }
    }
  }

  function onScroll(direction) {
    if(direction === 'up') {
      goSectionUp()
    } else {
      goSectionDown()
    }
  };

});
html {
box-sizing: border-box;
overflow: hidden;
width: 100%; height: 100%;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
padding: 0; margin: 0;
overflow: hidden;
height: 100%; width: 100%;
position: relative;
}



#page {
  width: 100%; height: 100%;
  transition: all 1s ease; 
  transform: none !important;
}

.section {
  height: 100vh; width: 100%;
  opacity: 0;
  visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  transition: all .7s ease-in-out;
}
.section:nth-of-type(1) {
  background-color: red;
}
.section:nth-of-type(2) {
  background-color: aquamarine;
}
.section:nth-of-type(3) {
  background-color: blueviolet;
}
.section:nth-of-type(4) {}

.active {
  opacity: 1; visibility: visible;
}


#button {
  position: sticky;
  top: 0; left: 100px;
  z-index: 1000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<div id="page">
  <div class="section">one</div>
  <div class="section">two</div>
  <div class="section">three</div>
  <div class="section">four</div>
</div>

最佳答案

看来您想要的是一个 debounce 函数。我建议使用这个,作者:David Walsh :

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

使用

var myScrollFunction = debounce(function() {
    // All the taxing stuff you do
}, 250);

document.addEventListener('wheel', myScrollFunction);

要回答为什么您的代码无法按预期工作:鼠标滚轮在滚动时会产生一系列连续事件,因此您的时间差异始终< 200。这是一个它“正常”工作的示例(尽管最好的答案仍然是如上所述的真正的去抖函数)。

JSBin 示例 https://jsbin.com/cuqacideto/edit?html,console,output

关于javascript - 事件处理程序被禁用的时间比预期的要长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410776/

相关文章:

javascript - 一次向 div 添加一个新字符,而不是使用 javascript 成堆添加

javascript - Conceal 滚动条并在悬停时显示,就像 facebook 的新聊天侧边栏一样

javascript - 三个JS raycaster,随着鼠标移动找到交叉点

c# - 如何区分Enter事件是由键盘还是鼠标点击引发的?

javascript - 使用 Ionic React 添加滚动按钮

具有固定导航栏偏移量的 Javascript 平滑滚动

javascript - 无法从 Javascript 获取 ASP.NET 4 中的隐藏元素

javascript - 点击获取高阶区 block 的id

jQuery.Event——我的数据在哪里?

javascript - 最小化后 if 语句不起作用