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

时间:2017-01-26 16:17:51

标签: 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) {

    }

  });

}());
&#13;
* {
  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;
}
&#13;
<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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您链接的示例实际上并不是一个非常长的页面,它只是窗口的大小。请注意,没有浏览器垂直滚动条。

它的作用是将自定义功能绑定到wheel事件:

window.addEventListener('wheel', function (event) {
    if (event.deltaY > 0) {

        // switch to next element

    } else if (event.deltaY < 0) {

        // switch to previous element

    }
});

这样,页面的“长”程度无关紧要。不需要<br><br><br><br>...眼睛。

答案 1 :(得分:0)

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

  2. 轮子事件将被多次触发,因此您只需处理一次此事件。跳过这些恼人事件的最简单方法是等待一秒钟。

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