如何在 css 中自动为文本高亮显示动画?

How to auto-animate text highlight in css?

我正在尝试在 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%;
  }
}

但它反而产生了一些奇怪的故障效果。我做错了什么以及如何实现?

您将需要使用一个伪元素(最好是 :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