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

如何为文字添加0.5透明度黑色背景并保留-webkit-mask-image动画效果

实现方案

通过对齐动画时序+绑定背景与文字容器的定位即可实现需求,无需大幅调整现有代码,仅需修改CSS规则,核心逻辑如下:

  • 给文字容器设置相对定位,作为背景的定位基准
  • 保留原有的-webkit-mask-image文字显示动画,统一文字动画与背景动画的时长、延迟、缓动参数
  • 调整背景元素定位规则,设置right:0实现宽度从左向右收缩的效果

完整实现代码

JSX代码

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <div className="text-animations">
        <div className="animation-text-wipe animate-in anim-delay">
          <div className="backdrop" />
          <p>
            周三发布的真实世界研究证实,接种两剂辉瑞新冠疫苗提供的免疫保护会在两个月左右后下降,不过对重症、住院和死亡的保护效力仍然保持较高水平。这些来自以色列和卡塔尔的研究发表在《新英格兰医学杂志》上,佐证了即便完成全程接种的人群也需要继续保持防护措施以避免感染的观点。以色列的一项研究覆盖了4800名医护人员,结果显示接种两剂疫苗后抗体水平迅速下降,“尤其是男性、65岁及以上人群,以及免疫抑制人群”。疫苗或已避免老年人群中25万例新冠感染、3.9万例死亡。“我们在以色列大型三级医疗中心示巴医疗中心开展了这项针对医护人员的前瞻性纵向队列研究”,示巴医疗中心的吉利·雷格夫-约哈伊博士及其同事在论文中写道。研究人员指出,所谓中和抗体——即免疫系统对抗感染的第一道防线——的水平与抗感染保护力相关,但本次研究仅针对抗体水平展开分析。
          </p>
        </div>
      </div>
    </div>
  );
}

CSS代码

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.App {
  padding: 2rem;
  background: #fff;
}

.text-animations {
  max-width: 800px;
}

.animation-text-wipe {
  position: relative;
  color: #000;
  font-size: 16px;
  line-height: 1.8;
  /* 文字擦除mask配置 */
  -webkit-mask-image: linear-gradient(to right, transparent 0%, #000 20%);
  -webkit-mask-size: 500% 100%;
  mask-image: linear-gradient(to right, transparent 0%, #000 20%);
  mask-size: 500% 100%;
}

.backdrop {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  background: rgba(0,0,0,0.5);
  z-index: -1;
}

/* 统一动画参数保证同步 */
.animate-in {
  animation: textWipe 2s ease forwards, backdropShrink 2s ease forwards;
}

.anim-delay {
  animation-delay: 0.5s;
}

/* 文字从左向右显示动画 */
@keyframes textWipe {
  0% {
    -webkit-mask-position: 100% 0;
    mask-position: 100% 0;
  }
  100% {
    -webkit-mask-position: 0 0;
    mask-position: 0 0;
  }
}

/* 背景从左向右收缩动画 */
@keyframes backdropShrink {
  0% {
    width: 100%;
  }
  100% {
    width: 0%;
  }
}

关键注意事项

  • 将背景元素放到文字容器内部,保证背景尺寸完全匹配文字内容,避免错位
  • 背景设置right:0后,宽度从100%降到0的过程就是从左向右收缩的效果,和文字显示进度完全匹配
  • 两个动画必须使用完全相同的时长、缓动函数、延迟参数,才能保证进度完全同步
  • 背景设置z-index:-1避免遮挡上层文字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:24:00