我希望在滚动时旋转一些元素。我希望它们从 0 度开始旋转,然后在每次向上/向下滚动事件时将当前度数加或减 25 度(或任何其他数字)。
这就是我所拥有的。它在第一次滚动时有效,但向上或向下滚动时该值不会更新。 我错过了什么?
const elem = document.querySelectorAll(".rotator");
window.addEventListener("scroll", function () {
elem.forEach((el) => {
let lastScrollTop = 0;
let value = 0;
let st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
// Scroll down
value += 25;
} else if (st < lastScrollTop) {
// Scroll up
value -= 25;
}
el.style.transform = `rotate(${value}deg)`;
})
})
.rotator {
height: 50px;
width: 50px;
background-color: lightgreen;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
height: 1000px;
}
<h1>Keep rotating on scrolling up or down</h1>
<div class="rotator">Rotate</div>
<div class="rotator">Rotate</div>
您在每次迭代中不断将值重置为
0
。将声明移到循环之外。
let value = 0;
let lastScrollTop = 0;
const elem = document.querySelectorAll(".rotator");
window.addEventListener("wheel", function () {
elem.forEach((el) => {
let st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
// Scroll down
value += 25;
} else if (st < lastScrollTop) {
// Scroll up
value -= 25;
}
console.log(value)
el.style.transform = `rotate(${value}deg)`;
})
})
.rotator {
height: 50px;
width: 50px;
background-color: lightgreen;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
height: 1000px;
}
<h1>Keep rotating on scrolling up or down</h1>
<div class="rotator">Rotate</div>
<div class="rotator">Rotate</div>