使动画悬停像过渡悬停

时间:2015-07-03 16:31:45

标签: css css-animations

当我的元素悬停时,我想将颜色变为灰色,然后变为浅绿色 当鼠标离开元素时:
如果我的元素是绿色,请转到灰色
如果我的元素是aqua,那么去绿色然后灰色 更准确我想要转换但3种颜色
当我们使用transtion改变2种颜色时 当鼠标离开元素时,结果很好,颜色逐渐变为灰色的第一个值 但是在动画中当鼠标离开元素颜色时非常快速变为灰色
解决方案是什么?

这是我的代码但不起作用。

@keyframes test {
  0% {
    background: gray;
  }
  50% {
    background: green;
  }
  100% {
    background: aqua;
  }
}
@keyframes test1 {
  0% {
    background: aqua;
  }
  50% {
    background: green;
  }
  100% {
    background: gray;
  }
}
.one {
  width: 300px;
  height: 300px;
  margin: 50px auto;
  background: gray;
  animation: test1 2s;
}
.one:hover {
  animation: test 2s alternate;
  animation-fill-mode: forwards;
}
<div class="one"></div>

2 个答案:

答案 0 :(得分:1)

您可以使用:before伪元素来覆盖背景。如果您将元素的不透明度设置为0作为默认值并设置为:hover上的1,则可以使用transition-delay在第一次完成时显示第二个转换。通过覆盖transition-delay上的:hover,您可以确保“mouseleave”也能正常运行。

像这样(仅在FireFox中测试):

.one {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 50px auto;
  background-color: gray;
  transition: background-color 1s linear 1s;
}
.one:before {
  content: "";
  display: block;
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: aqua;
  opacity: 0;
  transition: opacity 1s linear;
}
.one:hover {
  background-color: green;
  transition-delay: 0s;
}
.one:hover:before {
  opacity: 1;
  transition-delay: 1s;
}
<div class="one"></div>

答案 1 :(得分:0)

您可以将背景设置为渐变并为渐变位置设置动画

.test {
  width: 300px;
  height: 200px;
  background-size: 90000px 100%;
  background-image: linear-gradient(90deg, gray, green, aqua);
  background-position: 0% 0%;
  transition: background-position 2s;
}
.test:hover {
  background-position: 100% 0%;
  
}
<div class="test"></div>

相关问题