滚动插入新元素动画

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

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

背景

滚动插入新元素动画:当咱们滚动 滚动条 时,新的元素会以 左移右移淡出淡入 等各类方式插入到文档流中,若是再配合上 异步请求懒加载 效果将十分的出色,因此不管是在我的开发的 小项目,仍是在 企业界 都有被普遍的使用。今天咱们就一块儿来写一个简单的滚动插入新元素的动画吧。git

最终效果

滚动动画.gif

1、添加 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>
复制代码

2、添加 CSS 文件

先初始化页面github

  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 代码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;
}
复制代码

3、添加 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')
        }
    })
}
复制代码

❤️ 感谢你们

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

若是你喜欢这篇文章的话,能够「点赞」 + 「收藏」 + 「转发」 给更多朋友。post

相关文章
相关标签/搜索