使动画像过渡悬停一样悬停



当我的元素悬停时,我想将颜色从灰色改为绿色,然后改为浅绿色当鼠标离开元素时:
如果我的元素是绿色,则变为灰色
如果我的elemnt是浅绿色,则变为绿色,然后变为灰色
更准确地说,我想转换三种颜色
当我们使用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>

您可以使用:before伪元素来覆盖背景。如果将元素的不透明度设置为0作为默认值,并在:hover上设置为1,则可以使用transition-delay在第一次转换完成时显示第二次转换。通过覆盖:hover上的transition-delay,您可以确保"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>

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

.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>

相关内容

最新更新