简体   繁体   中英

CSS3 keep background color transitions the same

Various elements of the webpage have a background transition on them changing from color to color:

@-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;}
}

However, if an element is display: none and then displayed later through javascript, the color isn't consistent with the other elements, it starts the loop from the 0% color.

Is there a way to keep the transition universal? Thank you for your time.

Have you tried hiding the elements by making their opacity:0 and then setting it to 1 to unhide them? That should allow the background color to transition with all the other elements, but keep the element invisible.

Byh the way, the keyframes CSS directive is well supported by all major browsers at this point. There is no longer a need to use vendor prefixes with it.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM