滚动插入新元素动画

753 阅读2分钟

这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战

作者:battleKing
仓库:GithubCodePen
博客:CSDN掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权

背景

滚动插入新元素动画:当我们滚动 滚动条 时,新的元素会以 左移右移淡出淡入 等各种方式插入到文档流中,如果再配合上 异步请求懒加载 效果将十分的出色,所以无论是在个人开发的 小项目,还是在 企业界 都有被广泛的使用。今天我们就一起来写一个简单的滚动插入新元素的动画吧。

最终效果

滚动动画.gif

一、添加 HTML 文件

  1. 添加一层类名为 <h1></h1> ,用于存放标题
  2. 添加一层类名为 box<div>
  3. 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 文件

先初始化页面

  1. 设置 *box-sizing: border-box
  2. 设置 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 文件

主要逻辑

  1. 通过 document.querySelectorAll('.box'),获取全部类名为 box 的节点
  2. 通过 window.addEventListener('scroll', checkBoxes) 为滚动条绑定 checkBoxes方法
  3. 通过 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')
        }
    })
}

❤️ 感谢大家

如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。

如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。