这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战css
做者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经受权不得转载或抄袭,如需转载可联系笔者受权html
滚动插入新元素动画:当咱们滚动 滚动条
时,新的元素会以 左移
、右移
、淡出
、淡入
等各类方式插入到文档流中,若是再配合上 异步请求
和 懒加载
效果将十分的出色,因此不管是在我的开发的 小项目
,仍是在 企业界
都有被普遍的使用。今天咱们就一块儿来写一个简单的滚动插入新元素的动画吧。git
<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>
复制代码
先初始化页面github
*
为 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 代码markdown
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;
}
复制代码
主要逻辑异步
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')
}
})
}
复制代码
若是本文对你有帮助,就点个赞支持下吧,你的「赞」是我创做的动力。oop
若是你喜欢这篇文章的话,能够「点赞」 + 「收藏」 + 「转发」 给更多朋友。post