主要思路:让奇数的盒子左移至视窗外,偶数的盒子右移至视窗外,然后window对象添加滚动监听事件,滚动到相应区域,外移的盒子就移动回来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Animation</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Scroll to see the animation</h1>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<div class="box">
<h2>content</h2>
</div>
<script src="script.js"></script>
</body>
</html>
*{
box-sizing: border-box;
}
body{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-x: hidden;
}
/* h1{
margin: 10px;
} */
.box{
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 200px;
background-color: cyan;
color: #fff;
font-size: 32px;
margin: 10px;
border-radius: 10px;
box-shadow: 2px 4px 5px rgba(0,0,0,0.3);
transition: transform 2s ease;
}
/* 所有奇数元素 */
.box:nth-of-type(odd) {
transform: translateX(-400%);
}
/* 所有偶数元素 */
.box:nth-of-type(even) {
transform: translateX(400%);
}
.box.show{
transform: translateX(0);
}
const boxList = document.querySelectorAll('.box')
window.addEventListener('scroll', checkBox)
checkBox()
function checkBox() {
// window.innerHeight为浏览器内容区域高度
const showTop = window.innerHeight * 4 / 5
boxList.forEach(box => {
// box.getBoundingClientRect().top为box元素距离顶部的距离
const boxTop = box.getBoundingClientRect().top
if (boxTop < showTop) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
})
}
效果如下
Q.E.D.