在使用悬停转换时,CSS是否可以通过第三种颜色进行转换? [英] Is it possible in CSS to transition through a third color when using a hover transition?

查看:149
本文介绍了在使用悬停转换时,CSS是否可以通过第三种颜色进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在休息状态下为红色的元素,当用户将光标悬停在其上时,该元素为绿色。我把它设置为缓和 0.4s 的转换。



而不是直接从红色到绿色,我想它在中途穿过黄色。因此,当用户将鼠标悬停在其上时,它会在一个平滑过渡中从红色变为黄色,然后变为绿色。这是可能吗?



这是我目前的程式码。

 元素{
background-color:red;
-webkit-transition:all 0.4s ease;
transition:all 0.4s ease;
}
.element:hover {
background-color:green;
}


解决方案



  .element {background-color:red; height:300px; width:300px;}。element:hover {-webkit-animation:changeColor 0.4s forward;动画:changeColor 0.4s forward;} @keyframes changeColor {0%{background:red;} 50%{background:yellow} 100%{background:green} 50%{background:yellow} 100%{background:green}}  

 < div class =element>< / div>  






这是通过在元素悬停时添加关键帧序列,而不是在实际元素创建期间添加关键帧序列(因此关键帧只在悬停阶段工作)。 p>

使用 forward 声明,动画将在100%关键帧上暂停,而不是循环回到和完成它开始。也就是说第一个关键帧。






请注意:需要包含其他前缀详情请参阅这里


I have an element that is red in resting state, and green when the user hovers their cursor over it. I have it set to ease the transition for 0.4s.

Instead of having the colour transition straight from red to green, I'd like it to pass through yellow at the midway point. So when the user mouses over it, it goes from red to yellow to green in one smooth transition. Is this possible?

This is my current code.

.element {
    background-color: red;
    -webkit-transition: all 0.4s ease;
    transition: all 0.4s ease;
}
.element:hover {
    background-color: green;
}

解决方案

you could use keyframes for this:

.element {
  background-color: red;
  height: 300px;
  width: 300px;
}
.element:hover {  
  -webkit-animation: changeColor 0.4s forwards;
  animation: changeColor 0.4s forwards;
}

@-webkit-keyframes changeColor{
  0%{background: red;}
  50%{background:yellow}
  100%{background:green}
  }
@keyframes changeColor{
  0%{background: red;}
  50%{background:yellow}
  100%{background:green}
  }

<div class="element"></div>


This works by adding the keyframe sequence when the element is hovered, and not during the actual element's creation (so the keyframes only work during the hovered stage).

The forwards declaration is used so that the animation will 'pause' on the '100%' keyframe, rather than looping back and 'finishing where it started'. I.e. the first keyframe.


Please note: Other prefixes will need to be included see here for more info.

这篇关于在使用悬停转换时,CSS是否可以通过第三种颜色进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆