【问题标题】:How to auto-animate text highlight in css?如何在css中自动动画文本突出显示?
【发布时间】:2021-01-19 15:32:17
【问题描述】:

我正在尝试在 css 中创建一个文本突出显示动画,就像这个 gif 中的动画一样。从左到右不断。

我试过了

<p>
The <span class="test">world</span>
</p>


.test {
  background: linear-gradient(to top, red 50%, transparent 50%);
  animation-name: highlight;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}

@keyframes highlight {
  0% {
    background-size: 0;
    background-position: -100%, 0;
  }

  50% {
    background-size: 100%;
    background-position: 100%, 100%;
  }
}

但它会产生一些奇怪的故障效果。我做错了什么以及如何做到这一点?

【问题讨论】:

    标签: css css-animations css-transitions highlight


    【解决方案1】:

    您将需要使用一个伪元素(最好是 :after)并使用该伪元素的宽度。

    .test {
      position: relative;
    }
    .test:after {
      content: "";
      display: inline-block;
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: -1; /* Place the pseudo element right under the content */
      top: 0;
      left: 0;
      background: linear-gradient(to top, red 50%, transparent 50%);
      animation-name: highlight;
      animation-duration: 0.75s;
      animation-iteration-count: infinite;
      animation-direction: alternate; /* Make the animation run back and forth */
    }
    
    @keyframes highlight {
      0% {
        width: 0;
        opacity: 0;
      }
    
      50% {
        width: 100%;
        opacity: 1;
      }
    
    }
    <p>
    The <span class="test">world</span>
    </p>

    参考资料:

    Pseudo elements :after

    【讨论】:

    • 哇,帅哥。我想过使用 ::before 元素,但没有做到这一点。非常感谢!
    • 嗨,当我再次阅读您的答案时,我有一个问题(我是新手)。以 50% 结束关键帧元素会不会与动画方向相同?即它会重复自己...?
    • @Bluebug 您可以尝试禁用动画方向并检查产生的效果。
    • 啊,我错了。将最后一个关键帧设置为 50% 只会加快速度(2 倍)。方向实际上是回滚。
    • 没错!尝试花一些时间了解 CSS 动画属性并尝试不同的代码变体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2010-10-18
    • 2019-07-25
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多