我想在滚动时旋转一些元素。我希望它们从 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>