如何用纯 CSS 创作一个没有 DOM 元素的动画

忘是亡心i 2022-04-06 05:18 396阅读 0赞

在这里插入图片描述

效果预览

在线演示

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。

https://codepen.io/comehope/pen/JBqjqm

可交互视频

此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。

请用 chrome, safari, edge 打开观看。

https://scrimba.com/p/pEgDAM/cD3KwTw

源代码下载

本地下载

每日前端实战系列的全部源代码请从 github 下载:

https://github.com/comehope/front-end-daily-challenges

代码解读

没有 dom 元素,直接写 css。
设置页面空间:

  1. body {
  2. position: fixed;
  3. margin: 0;
  4. width: 100vw;
  5. height: 100vh;
  6. }

用伪元素设置背景图案:

  1. body::before {
  2. content: '';
  3. position: fixed;
  4. width: 200vmax;
  5. height: 200vmax;
  6. background-color: steelblue;
  7. color: turquoise;
  8. background-image:
  9. linear-gradient(
  10. 45deg,
  11. currentColor 25%,
  12. transparent 25%, transparent 75%,
  13. currentColor 75%),
  14. linear-gradient(
  15. 45deg,
  16. currentColor 25%,
  17. transparent 25%, transparent 75%,
  18. currentColor 75%);
  19. background-position: 0 0, 5vmax 5vmax;
  20. background-size: 10vmax 10vmax;

平移背景图案:

  1. body::before {
  2. top: 50%;
  3. left: 50%;
  4. animation:
  5. 9s move infinite ease-in-out alternate;
  6. }
  7. @keyframes move {
  8. from {
  9. left: -40%;
  10. top: -40%;
  11. }
  12. to {
  13. left: -60%;
  14. top: -60%;
  15. }
  16. }

让背景图案转动起来:

  1. body::before {
  2. animation:
  3. 9s move infinite ease-in-out alternate,
  4. 9s -1.5s rotating infinite ease-in-out alternate;
  5. }
  6. @keyframes rotating {
  7. to {
  8. transform: rotate(180deg);
  9. }
  10. }

平移页面:

  1. body {
  2. top: 50%;
  3. left: 50%;
  4. animation:
  5. 3s move infinite ease-in-out alternate;
  6. }

缩放页面:

  1. body {
  2. animation:
  3. 3s move infinite ease-in-out alternate,
  4. 3s zoom infinite ease-in-out alternate;
  5. }
  6. @keyframes zoom {
  7. to {
  8. transform: scale(10);
  9. }
  10. }

最后,增加变色效果:

  1. @keyframes rotating {
  2. to {
  3. transform: rotate(180deg);
  4. filter: hue-rotate(1turn);
  5. }
  6. }

大功告成!

原文地址:https://segmentfault.com/a/1190000016013632

发表评论

表情:
评论列表 (有 0 条评论,396人围观)

还没有评论,来说两句吧...

相关阅读