这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战
作者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权
背景
滚动插入新元素动画:当我们滚动 滚动条 时,新的元素会以 左移、右移、淡出、淡入 等各种方式插入到文档流中,如果再配合上 异步请求 和 懒加载 效果将十分的出色,所以无论是在个人开发的 小项目,还是在 企业界 都有被广泛的使用。今天我们就一起来写一个简单的滚动插入新元素的动画吧。
最终效果
一、添加 HTML 文件
- 添加一层类名为
<h1></h1>,用于存放标题 - 添加一层类名为
box的<div> box里面添加一层<h2></h2>,用于存放新插入的元素
<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>
<div class="box">
<h2>Content</h2>
</div>
二、添加 CSS 文件
先初始化页面
- 设置
*为box-sizing: border-box - 设置
body来使页面为米黄色且整个项目居中对齐
* {
box-sizing: border-box;
}
body {
background-color: #efedd6;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
overflow-x: hidden;
}
主要的 CSS 代码
h1 {
margin: 10px;
}
.box {
background-color: steelblue;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
width: 400px;
height: 200px;
margin: 10px;
border-radius: 10px;
box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3);
transform: translateX(400%);
transition: transform 0.4s ease;
}
.box:nth-of-type(even) {
transform: translateX(-400%);
}
.box.show {
transform: translateX(0);
}
.box h2 {
font-size: 45px;
}
三、添加 JS 文件
主要逻辑
- 通过
document.querySelectorAll('.box'),获取全部类名为box的节点 - 通过
window.addEventListener('scroll', checkBoxes)为滚动条绑定checkBoxes方法 - 通过
checkBoxes()方法实现滚动插入新元素效果
const boxes = document.querySelectorAll('.box')
window.addEventListener('scroll', checkBoxes)
checkBoxes()
function checkBoxes() {
const triggerBottom = window.innerHeight / 5 * 4
boxes.forEach(box => {
const boxTop = box.getBoundingClientRect().top
if (boxTop < triggerBottom) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
})
}
❤️ 感谢大家
如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。
如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。