CSS3:背景颜色向透明的过渡

6
我想在一个 div 中进行过渡,它应该:
  • background-color:rgba(242, 245, 169, 1); 开始

    ... 然后经过3秒钟...

  • background-color:rgba(242, 245, 169, 0); 结束

在两个阶段之间显示 background-color:rgba(242, 245, 169, 0.9);background-color:rgba(242, 245, 169, 0.8);background-color:rgba(242, 245, 169, 0.7); ...

类似于 这个解决方案 ,但没有 ':hover'。直接实现。

我该如何实现?

谢谢。


2
你需要使用动画而不是过渡。 - romuleald
2
看一下关键帧。那就是你想要的。 - Bram Vanroy
哦,非常感谢! - Aral Roca
http://www.w3schools.com/css/css3_animations.asp - Sid Shukla
3个回答

17

http://jsfiddle.net/BramVanroy/hakomq5L/

div {
    width: 100px;
    height: 100px;
    animation: fade 3s forwards;
    background-color:rgba(242, 245, 169, 1);
}

@keyframes fade {
    from {background-color:rgba(242, 245, 169, 1);}
    to {background-color:rgba(242, 245, 169, 0);}
}

2

只需使用动画即可。我的解决方案是可重复使用的,因为我使用了不透明度属性,所以您可以使用任何颜色。

工作的JSFIDDLE:http://jsfiddle.net/5m1pb227/1/

HTML

<div class="box">

CSS

.box {
  background-color:rgb(242, 245, 169);
  width:100px; height:100px;
  position: relative;
  animation: myfadeIn 2s;  
}


@keyframes myfadeIn {
  0%   { opacity: 1; }
  100% { opacity: 0; }
}

0
除了其他正确的答案之外,如果悬停元素不是一个 div 而是一个链接,并且您正在从 rgba 颜色进行过渡,Chrome 62 将不会对其进行过渡,除非您指定该链接不是内联的,即:

CSS

a {display:inline-block;}

如果将hover元素保持内联显示,Chrome无法对过渡进行动画处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接