CSS3 保持背景颜色过渡相同



网页的各个元素都有一个背景过渡,从颜色到颜色:

@-moz-keyframes backgroundTransition /* Firefox */ {
    0%   {background-color:#ff7b7b;}
    33%   {background-color:#7fceff;}
    66%   {background-color:#80e880;}
    100%   {background-color:#ff7b7b;}
}
@-webkit-keyframes backgroundTransition /* Safari and Chrome */{
    0%   {background-color:#ff7b7b;}
    33%   {background-color:#7fceff;}
    66%   {background-color:#80e880;}
    100%   {background-color:#ff7b7b;}
}

但是,如果一个元素被display: none,然后通过javascript显示,则颜色与其他元素不一致,它会从0%颜色开始循环。

有没有办法保持过渡的普遍性?谢谢你的时间。

您是否尝试过通过opacity:0元素然后将其设置为1来隐藏元素以取消隐藏它们?这应该允许背景颜色与所有其他元素一起过渡,但使元素不可见。

顺便说一下,在这一点上,所有主流浏览器都很好地支持 keyframes CSS 指令。不再需要使用供应商前缀。

document.querySelector("button").addEventListener("click", function(){
  document.querySelector(".hidden").classList.remove("hidden");
});
div {
  width:50px;
  height:50px;
  background-color:black;
  border:1px solid black;
  
  animation-duration: 8s;
  animation-name: backgroundTransition;
}
/* The hidden elements will not take up space in the
   normal document flow and will not be visible because
   the will be 100% transparent. Simply removing this 
   class when its time to see the element(s) puts them
   back into the normal flow and their background will
   be the same as all the other div elements. */
.hidden { opacity:0; position:absolute; }
@keyframes backgroundTransition{
	0%   {background-color:#ff7b7b;}
  33%   {background-color:#7fceff;}
  66%   {background-color:#80e880;}
  100%   {background-color:#ff7b7b;}
}
<div></div>
<div class="hidden"></div>
<div></div>
<button>Click me during the animation to reveal the hidden div,<br>which will have its color in sync with the other div elements</button>

我认为你不能使用可见性 css 属性来处理它,或者你不能 cuz 每当它被渲染时,它将从 0

opacity: 0

height:0; width:0;

z-index: <val>

最新更新