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

如何用CSS实现从左到右的背景淡入效果?React重渲染时生效

问题:实现React组件从左到右的淡入效果

我在开发React应用,希望组件的背景和文本从左侧开始淡入,逐步过渡到右侧完全显示。仅使用opacity会让整个组件背景同时变化,无法实现从左到右的渐变效果;尝试使用translateY(10px)会移动整个组件,而我需要边框保持固定位置。当前代码如下:

.box{
  border: 3px solid #fff0f179;
  border-radius: 3px;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 44px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 44px;
  margin: 3px;
   font: 800 24px ;
  -webkit-text-fill-color: white;
  -webkit-text-stroke: 1px;
  animation: fadeBackground 5s ease;
}
@keyframes fadeBackground {

        /* 0% {opacity:0%}
        40% {opacity:40%}
        60% {opacity:60%;}
        100% {opacity:100%;} */

    0%{
         opacity: 0;
        transform: translateY(10px);
        background-color: white;
    }
    100%{
        opacity: 1;
          transform: translateY(0);
    }
}

请问该如何实现所需的从左到右淡入效果?

解决方案

方法一:伪元素遮罩滑动法

这种方法能完美保留边框固定,通过遮罩层从左向右滑动,逐步露出组件的背景与文本。

修改后的CSS代码:

.box{
  border: 3px solid #fff0f179;
  border-radius: 3px;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 44px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 44px;
  margin: 3px;
  font: 800 24px;
  -webkit-text-fill-color: white;
  -webkit-text-stroke: 1px;
  background-color: white;
  position: relative;
  overflow: hidden;
}

.box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* 替换为组件所在容器的背景色 */
  background-color: #页面背景色;
  animation: slideMask 5s ease forwards;
}

@keyframes slideMask {
  0% { transform: translateX(0); }
  100% { transform: translateX(100%); }
}

关键说明:

  • 伪元素作为遮罩层,初始完全覆盖组件,动画结束后完全滑出组件范围。
  • 遮罩色必须与页面背景色一致,才能实现"淡入"的视觉效果。

方法二:背景渐变位移动画法

通过渐变背景的位置动画,实现背景从左到右逐步显现,同时配合文本透明度动画。

修改后的CSS代码:

.box{
  border: 3px solid #fff0f179;
  border-radius: 3px;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 44px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 44px;
  margin: 3px;
  font: 800 24px;
  -webkit-text-fill-color: white;
  -webkit-text-stroke: 1px;
  background: linear-gradient(to right, white 0%, white 0%, transparent 0%);
  background-size: 200% 100%;
  animation: fadeBackground 5s ease forwards;
  opacity: 0;
}

@keyframes fadeBackground {
  0% {
    background-position: 100% 0;
    opacity: 0;
  }
  100% {
    background-position: 0 0;
    opacity: 1;
  }
}

关键说明:

  • 利用background-position的变化,让白色背景从右侧逐步移动到左侧,覆盖整个组件。
  • 文本的透明度动画与背景动画同步,保证整体视觉统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:53:15