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

纯CSS实现悬停移入移出均从左到右的淡入淡出效果

纯CSS实现同方向从左到右悬停淡入淡出效果

目标淡入淡出效果演示

问题原因

你当前的代码实现天然无法满足需求:靠background-position做过渡,本质是在「右定位」「左定位」两个固定状态之间做线性补间,鼠标移出时属性值要从hover态的左定位回到默认态的右定位,动画会沿原路返回,自然就出现了从右到左的反向淡出效果。

实现方案

不要使用可双向补间的transition直接控制背景位置,改用伪元素做分层背景,分别给鼠标移入、移出状态配置同方向运动的动画即可,完整代码如下:

/* 可根据项目实际需求替换变量值 */
:root {
  --btn-prim-bg-color: #165DFF;
  --color-primary: #FFFFFF;
  --color-text: #1D2129;
}

input[type='submit'] {
  /* 基础按钮样式,默认状态即为非hover的最终展示态 */
  position: relative;
  padding: 10px 28px;
  border: none;
  border-radius: 4px;
  background: var(--btn-prim-bg-color);
  color: #fff;
  text-transform: uppercase;
  cursor: pointer;
  overflow: hidden;
  /* 文字颜色单独做平滑过渡 */
  transition: color .5s ease;
  z-index: 1;
}

/* hover状态的背景层,层级低于按钮文字 */
input[type='submit']::before {
  content: '';
  position: absolute;
  inset: 0;
  background: var(--color-primary);
  z-index: -1;
  /* 默认藏在按钮左侧可视区域外 */
  transform: translateX(-100%);
}

/* 鼠标移入:播放从左到右铺入动画 */
input[type='submit']:hover {
  color: var(--color-text);
}
input[type='submit']:hover::before {
  animation: fadeSlideIn .5s forwards ease;
}

/* 鼠标移出:播放从左到右滑出动画 */
input[type='submit']:not(:hover)::before {
  animation: fadeSlideOut .5s forwards ease;
}

@keyframes fadeSlideIn {
  from { transform: translateX(-100%); }
  to { transform: translateX(0); }
}

@keyframes fadeSlideOut {
  from { transform: translateX(0); }
  to { transform: translateX(100%); }
}

效果逻辑

  • 鼠标移入时:hover态背景从按钮左边缘进入,向右移动铺满整个按钮,同步完成文字颜色切换,呈现从左到右的淡入效果
  • 鼠标移出时:hover态背景不会反向回退,而是继续向右移动,从按钮右边缘滑出露出默认底色,运动方向始终保持从左到右,和参考动图效果完全一致

小优化:如果不想页面刚加载的时候按钮自动触发一遍移出动画,等DOM加载完成后给按钮加个类似is-ready的类,把两个动画的绑定规则限定在该类下即可,不影响核心实现逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:06:10