如何使用CSS实现眼冒金星的动画效果(附源码)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用CSS实现眼冒金星的动画效果(附源码),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2714字,纯文字阅读大概需要4分钟。
内容图文
![如何使用CSS实现眼冒金星的动画效果(附源码)](/upload/InfoBanner/zyjiaocheng/418/500598105aa34eb39bb06c192f1a1324.jpg)
效果预览
源代码下载
https://github.com/comehope/front-end-daily-challenges
代码解读
定义 dom,容器中包含 9 个子元素:
<div class='container'> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div>
居中显示:
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: black; }
设置容器中子元素的布局方式,形成一个 3 * 3 的网格,其中 --columns
是网格每一边上的子元素数量:
.container { display: grid; --columns: 3; grid-template-columns: repeat(var(--columns), 1fr); }
定义子元素样式:
.container span { width: 25px; height: 25px; color: lime; background-color: currentColor; }
增加子元素的动画效果,总动画时长是 5 秒,其中第 1 秒(0% ~ 20%)有动画,其余 4 秒(20% ~ 100%)静止:
.container span { transform: scale(0); animation: spin 5s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg) scale(1); } 5%, 15% { transform: rotate(90deg) scale(0); background: white; } 17.5% { transform: rotate(180deg) scale(1); background-color: currentColor; } 20%, 100% { transform: rotate(90deg) scale(0); } }
设置动画延时,使各子元素的动画随机延时 4 秒之内的任意时间:
.container span { animation-delay: calc(var(--delay) * 1s); } .container span:nth-child(1) { --delay: 0.8 } .container span:nth-child(2) { --delay: 0.2 } .container span:nth-child(3) { --delay: 1.9 } .container span:nth-child(4) { --delay: 3.9 } .container span:nth-child(5) { --delay: 2.8 } .container span:nth-child(6) { --delay: 3.5 } .container span:nth-child(7) { --delay: 1.5 } .container span:nth-child(8) { --delay: 2.3 } .container span:nth-child(9) { --delay: 1.7 }
至此,静态效果完成,接下来批量处理 dom 元素。
引入 d3 库:
<script src="https://d3js.org/d3.v5.min.js"></script>
删除掉 css 文件中的 --columns
变量声明,用 d3 为变量赋值:
const COLUMNS = 3; d3.select('.container') .style('--columns', COLUMNS);
删除掉 html 文件中的 <span>
子元素,用 d3 动态生成:
d3.select('.container') .style('--columns', COLUMNS) .selectAll('span') .data(d3.range(COLUMNS * COLUMNS)) .enter() .append('span');
删除掉 css 文件中的 --delay
变量声明,用 d3 为变量生成随机数:
d3.select('.container') .style('--columns', COLUMNS) .selectAll('span') .data(d3.range(COLUMNS * COLUMNS)) .enter() .append('span') .style('--delay', () => Math.random() * 4);
最后,把边长改为 15,生成更多的子元素,加强视觉效果:
const COLUMNS = 15;以上就是本篇文章的全部内容了,关于上述代码中所用到的css知识大家可以参考Gxlcms的css开发手册。
以上就是如何使用CSS实现眼冒金星的动画效果(附源码)的详细内容。
内容总结
以上是互联网集市为您收集整理的如何使用CSS实现眼冒金星的动画效果(附源码)全部内容,希望文章能够帮你解决如何使用CSS实现眼冒金星的动画效果(附源码)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。