css 实现圆圈聚焦效果

1,817 阅读3分钟

通过 纯CSS 动画技术,创建的一个文字动态效果,文字从右到左移动,每循环一次方向反转,给人一种视觉上的动感

下面是先看代码实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div class="animation"></div>

  <style>
    .animation {
      width: fit-content;
      font-weight: bold;
      font-size: 30px;
      background: radial-gradient(circle closest-side, #000 94%, #0000) right/calc(200% - 1em) 100%;
      /* animation: focusing 1s infinite alternate linear; */
      animation-duration: 1s;
      animation-timing-function: linear;
      animation-delay: 0s;
      animation-iteration-count: infinite;
      animation-direction: alternate;
      animation-play-state: running;
      animation-name: focusing;
    }

    .animation::before {
      content: "iwhao...";
      line-height: 1em;
      color: #0000;
      background: inherit;
      background-image: radial-gradient(circle closest-side, #fff 94%, #000);
      -webkit-background-clip: text;
      background-clip: text;
    }

    @keyframes focusing {
      100% {
        background-position: left
      }
    }
  </style>

</body>

</html>

效果 代码逐行分析

  • width: fit-content; 确保元素宽度随内容自适应。
  • font-weight: bold; 使文字显得更粗重。
  • font-size: 30px; 设置字体大小。
  • background: radial-gradient(...); 创建一个从黑色到黑色的径向渐变,从右向左延伸,覆盖整个元素。
  • animation- 属性是关键,定义了动画的名称、持续时间、重复次数、方向、速度曲线和延迟。

动画效果

上面代码有注释部分,简写代码为

animation: focusing 1s infinite alternate linear; 

拆解写法

  • animation-duration: 1s; 设置动画的持续时间。
  • animation-timing-function: linear; 表示动画的速度曲线为线性,即动画速度在整个过程中保持匀速。
  • animation-delay: 0s; 无延迟开始动画。
  • animation-direction: alternate; 每次循环,动画方向都会改变,从左到右再到左,如此循环。
  • animation-play-state: running; 确保动画一开始就处于运行状态。

整体表达的就是 定义了动画名为 focusing,持续时间为1秒,无限重复,交替播放(每次循环方向相反),并以线性速度进行。 文字效果

.animation::before 伪元素用于在文字前创建一个与背景相同的径向渐变,通过 -webkit-background-clip: text; 和 background-clip: text; 实现文字颜色与背景渐变的无缝融合。

关键帧动画(@keyframes)

  • @keyframes focusing 定义了一个名为 focusing 的关键帧动画,仅包含一个关键帧(100%)。
  • 100% { background-position: left; } 当动画进行到100%时,背景的位置会从右移动到左,从而实现文字的移动效果。

动画持续时间:动画持续时间设定为 1s,即动画从开始到结束共执行 1 秒

动画速度曲线:动画速度曲线定义了动画在执行过程中的速度变化。在这里,我们使用了 linear,这意味着动画在整个过程中以恒定的速度执行

动画重复次数:在这里,我们使用了 infinite,这意味着动画会无限次重复

动画方向:动画方向定义了动画在每次重复时的方向。在这里,我们使用了 alternate,这意味着动画会在奇数次重复时从左向右执行,在偶数次重复时从右向左执行

动画延迟:动画延迟定义了动画在开始执行之前的等待时间。在这里,我们使用了 0s,这意味着动画会立即开始执行

动画播放状态:动画播放状态定义了动画是否正在执行。在这里,我们使用了 running,这意味着动画会在加载页面时立即开始执行