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

鼠标移开元素后缓慢恢复初始样式的CSS动画实现

实现鼠标移出时背景色缓慢恢复的效果

你当前的问题是仅通过@keyframes实现了hover时的变色动画,但未定义鼠标移出时的过渡逻辑,导致元素样式会立即重置。以下是两种可行的解决方案:

方案一:使用CSS Transition(推荐,简洁易维护)

Transition原生支持状态切换的双向过渡,只需为元素设置过渡属性,并在hover状态下调整过渡时长即可:

修改后的CSS代码:

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

html {
    font-size: 62.5%;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.fst--row {
    width: 80rem;
    height: 20rem;
    display: flex;
    gap: 0.7rem;
}

.fst--row>div {
    width: 50%;
    height: 100%;
    /* 鼠标移出时,用2秒恢复初始背景色 */
    transition: background-color 2s ease;
}

.fst--row>div:nth-child(1) {
    background-color: #099268;
}

.fst--row>div:nth-child(2) {
    background-color: #e67700;
}

.fst--row>div:hover {
    background-color: red;
    /* hover时,用1秒切换为红色 */
    transition-duration: 1s;
}

方案二:使用CSS Animation(保留原动画逻辑)

如果坚持使用@keyframes实现,需要定义反向动画,并通过animation属性控制hover和移出时的动画切换:

修改后的CSS代码:

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

html {
    font-size: 62.5%;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.fst--row {
    width: 80rem;
    height: 20rem;
    display: flex;
    gap: 0.7rem;
}

.fst--row>div {
    width: 50%;
    height: 100%;
    /* 默认应用恢复动画,维持初始状态 */
    animation: reset--flex 2s forwards;
}

.fst--row>div:nth-child(1) {
    background-color: #099268;
}

.fst--row>div:nth-child(2) {
    background-color: #e67700;
}

.fst--row>div:hover {
    /* hover时覆盖恢复动画,播放变色动画 */
    animation: hover--flex 1s forwards;
}

@keyframes hover--flex {
    to {
        background-color: red;
    }
}

@keyframes reset--flex {
    from {
        background-color: red;
    }
    to {
        background-color: inherit;
    }
}

补充说明

  • 方案一适合这类简单的状态切换场景,代码量少且逻辑直观。
  • 方案二更适合需要复杂动画时序或多阶段变化的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:46:14