javascript - 为什么我的 JavaScript 向上/向下滚动事件不起作用?

标签 javascript html css events scroll

我正在尝试制作类似 this website 的效果当您向下滚动时,侧边导航元素获得一个 active 类,并且在之前该类被删除。我的代码中的问题是,当我向下滚动时,它只滚动到下一个元素,然后不想从那里移动...

这是我的片段:

(function() {

  // scroll container elements
  var parent_el = document.getElementById('container');
  var el = document.getElementsByClassName('line');

  window.addEventListener('wheel', function(event) {
    var count = 0;

    if (event.deltaY > 0) {

      if (el.item(count).classList.contains('current')) {
        el.item(count).classList.remove('current');
      }
      count++;
      el.item(count).classList.add('current');
    } else if (event.deltaY < 0) {

    }

  });

}());
* {
  box-sizing: border-box;
}
body {
  background: #000;
}
::-webkit-scrollbar {
  display: none;
}
::scrollbar {
  display: none;
}
*,
html,
body {
  margin: 0;
  padding: 0;
}
.line-container {
  width: 100px;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: flex;
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.line {
  width: 25px;
  height: 5px;
  background: #fff;
  margin-bottom: 1.5em;
  cursor: pointer;
  transition: all 350ms ease-in-out;
}
.current {
  width: 45px;
  background: #FFFFFF;
  transition: all 350ms ease-in-out;
}
.long {
  height: 5000px;
  width: 100%;
  position: relative;
}
<div class="line-container" id="container">
  <div class="line current"></div>
  <div class="line"></div>
  <div class="line"></div>
  <div class="line"></div>
  <div class="line"></div>
</div>
<div class="long"></div>

最佳答案

  1. 您必须将变量“count”移出 addEventListener 回调函数,因为该函数总是将 count 重置为零。

  2. wheel 事件会被多次触发,所以你只需要处理一次这个事件。跳过这些烦人事件的最简单方法是等待一秒钟。

    var count = 0, wait = 300, animationStartTime = 0; window.addEventListener('wheel', function(event) { var now = (new Date()).getTime(); if (now - animationStartTime < wait) { // Wait for the animation and skip wheel event util the animation is completed. return; } if (event.deltaY > 50) { animationStartTime = (new Date()).getTime(); ... }

关于javascript - 为什么我的 JavaScript 向上/向下滚动事件不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878044/

相关文章:

javascript - trim 对象中的所有值;错误: Cannot set property of undefined

html - 浏览器是在解析 css 时还是在形成规则后请求图像?

html - 自定义 css 光标过渡

css - Sass @extend 行为类似于 LESS 和 @import

html - 为什么 Chrome 移动我的表单标签并在选择接收焦点时选择?

javascript - 如何允许用户从我的 JavaScript/PhoneGap 应用程序向 Twitter 发帖?

javascript - docker 未在主机上安装依赖项(node_modules)

javascript - 在我将 javascript 添加到导航组件后,HTML href 链接不起作用

html - 当我的 DIV 包含图像时如何应用垂直居中?

html - CSS 连字符抛出错误(无效的属性值)