我正在尝试制作类似 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>
最佳答案
您必须将变量“count”移出 addEventListener 回调函数,因为该函数总是将 count 重置为零。
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/