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

如何实现invert滤镜(黑转白)的平滑过渡效果?

解决图标filter过渡无平滑效果的问题

问题出在两个核心点:

  • 过渡规则被加在了.links父容器上,但实际应用filter属性变化的是<img>元素,过渡必须作用在实际发生样式变更的元素上才会生效。
  • <img>元素没有设置初始filter值,浏览器无法识别过渡的起始状态,只能直接跳变。

修改方案:

把过渡规则移到<img>的基础样式中,并定义初始filter值,让过渡逻辑正确触发:

/* 给图标设置初始状态和过渡规则 */
.icon {
  filter: invert(0%); /* 初始状态:保持黑色,不反转 */
  transition: filter 500ms ease-in-out; /* 明确过渡属性、时长和曲线 */
}

.link-trans {
  /* 仅负责修改filter值,过渡规则已在.icon中定义 */
  filter: invert(100%) !important; /* 加!important确保优先级,或调整选择器权重 */
}

/* 移除.links类中的过渡相关规则,因为不需要 */
.links {
  display: flex;
  justify-content: space-between;
  margin-left: 15px;
  margin-right: 15px;
}

/* 保留原有其他样式 */
.usercard {
  width: 310px;
  box-shadow: 0 0 5px 2px rgb(233, 233, 233);
  background-color: rgb(233, 233, 233);
  border: solid 5px rgb(233, 233, 233);
  border-radius: 5px;
  transition-duration: 500ms;
  transition-timing-function: ease-in-out;
}

.usercard:hover {
  color: azure;
  border-color: rgb(18, 18, 18);
  background-color: rgb(18, 18, 18);
  transform: scale(1.1);
  margin-left: 20px;
  margin-right: 20px;
}

.main {
  display: flex;
  justify-content: space-between;
  margin-left: 100px;
  margin-right: 100px;
  margin-top: auto;
  transform: translateY(15%);
}

补充优化:

如果需求是在usercard hover时触发图标反转,完全可以不用JS添加类,直接用CSS选择器实现,逻辑更简洁:

.usercard:hover .icon {
  filter: invert(100%);
}

这种方式下,过渡规则依然保留在.icon类中即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:27:41