You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何同时实现渐变文字与文字扫光效果?

实现渐变文字与扫光文字效果共存的方案

问题

需要同时实现两种独立的文字效果:

  1. 渐变文字:文字呈现自定义颜色渐变
  2. 扫光动画:白色高光从文字左侧滑至右侧的循环动画
    两种效果颜色不同,但由于都依赖background和-webkit-background-clip: text属性,直接设置会互相覆盖,无法同时生效。

解决方案:伪元素分层实现

核心思路是通过伪元素将两种效果分离到不同层级:原元素承载渐变文字,伪元素叠加在上方实现扫光动画,两者独立设置背景属性,避免冲突。

完整代码示例

HTML结构

<h1 class="gradient-shine" data-text="Hello World">Hello World</h1>

CSS样式

.gradient-shine {
  font-size: 72px;
  /* 底层:渐变文字效果 */
  background: -webkit-linear-gradient(#eee, #333);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
  /* 确保伪元素相对于当前元素定位 */
}

.gradient-shine::after {
  /* 复制原文字内容 */
  content: attr(data-text);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 上层:扫光动画效果 */
  background: #222 -webkit-gradient(linear, left top, right top, from(#222), to(#222), color-stop(0.5, #fff)) 0 0 no-repeat;
  -webkit-background-size: 150px;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  /* 执行扫光动画 */
  animation: shine 3s infinite linear;
}

/* 定义扫光动画关键帧 */
@keyframes shine {
  0% {
    background-position: -100% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

原理说明

  • 原元素:通过-webkit-linear-gradient设置渐变背景,配合-webkit-background-clip: text和-webkit-text-fill-color: transparent实现渐变文字效果。
  • 伪元素::after:通过attr(data-text)继承原元素的文字内容,绝对定位覆盖在原元素上方,单独设置扫光背景和动画逻辑,同样使用-webkit-background-clip: text让背景仅显示在文字区域,最终实现两种效果的叠加展示。

内容的提问来源于stack exchange,提问作者Shade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 01:17:25