有以下代码:
function startAnimation() {
var box = document.querySelector('.box');
var boxPosition = box.getBoundingClientRect().top;
var screenPosition = window.innerHeight / 1.2;
if(boxPosition < screenPosition) {
box.classList.add('animation');
}
}
window.addEventListener('scroll', startAnimation);
@keyframes rotate {
100% {
transform: rotate(180deg);
}
}
.box.animation {
animation: rotate 1s ease-in 0.1s;
animation-fill-mode: forwards;
}
.container {
background-color: #03A9F4;
height: 2000px;
}
.box-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 490px;
border: 5px solid #FFEB3B;
}
.box {
width: 100px;
height: 100px;
background-color: #8BC34A;
border: 5px solid #4CAF50;
}
<div class="container">
<div class="box-wrapper">
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
</div>
你能告诉我如何让每个 .box 出现在屏幕上时旋转吗?我知道所有 .box 都需要放入一个数组中,但我不知道接下来要对数组做什么......
结果证明解决方案比我想象的要简单)
querySelector只找到页面上的第一个指定元素。要查找所有内容,您需要使用querySelectorAll(). 它已经“几乎”返回了一个数组(演示):
在您的情况下,盒子元素既被创建又保持在原位。因此,每次都不能在函数内部重新创建变量,而是将其从其限制中取出。
演示工作
for()Ps 在所有动画完成后禁用该功能会很好......所以它不会在每次滚动时都检查这么多东西。但我不知道如何。)