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

CSS :hover添加transition仅移入生效,鼠标移出无过渡如何解决?

问题根因

你当前的transition属性仅定义在.required:hover::after规则中,该属性仅当元素处于鼠标悬浮状态时才会生效:

  • 光标移入元素触发hover状态时,transition规则生效,因此平移会有1秒的过渡动画
  • 光标移出元素时,hover状态失效,对应的transition规则也一同消失,元素回到初始样式的过程没有过渡属性控制,就会直接跳回初始位置
解决方案

将transition: 1s规则从悬浮态选择器移动到.required::after的默认态选择器中即可。修改后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <style>
            .required::before {
                content: '';
                display:block;
                width: 10px;
                height: 10px;
                background-color: red;
                border-radius:10px;
            }
            .required::after {
                content: '';
                display:inline-block;
                width: 10px;
                height: 10px;
                background: blue;
                margin-left: -20px;
                /* transition放在默认态,所有状态切换都会触发过渡 */
                transition: 1s;
            }
            .required:hover::after{
                transform: translateX(100px);
            }
        </style>
    </head>

    <body>
        <label class = required>Name</label>
    </body>
</html>
扩展说明

如果需要自定义悬浮入场、离场的不同过渡时长,可以分别在两个状态下配置transition:比如入场动画0.3秒,离场动画1.5秒,只需要在默认态写transition: 1.5s,在:hover态写transition: 0.3s即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:00:02