首页 > 解决方案 > CSS - 来回动画 css 设置

问题描述

如果您将鼠标悬停在我的示例中的框上,那么小框的颜色会慢慢地从红色变为黄色。但如果你停止悬停,它会立即跳回红色。

.container { position: relative; background: black; width: 200px; height: 200px; }
.subcontainer { position: absolute; bottom: 10px; width: 100%; height: 20px; background: red; animation-duration: 2s; }

.container:hover .subcontainer { background: yellow; animation-duration: 2s; animation-name: example; }

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
<div class="container">
  <div class="subcontainer">

  </div>
</div>

如何防止这种即时颜色变化?我也尝试添加animation-duration: 2s;.subcontainer但它不起作用。

标签: csscss-animations

解决方案


你需要一个transition定义在.subcontainer而不是animation

.container { 
    position: relative; 
    background: black; 
    width: 200px; height: 200px; }

.subcontainer { 
    position: absolute; 
    bottom: 10px; width: 100%; height: 20px; 
    background: red; 
    transition: background 2s 0s }

.container:hover .subcontainer { background: yellow;  }
<div class="container">
  <div class="subcontainer">

  </div>
</div>


推荐阅读