2017-05-27 1967 views
0

我該如何編寫代碼來動態更改HTML中元素的顏色。 例如:如果你好是標籤,從最初2秒,應以過渡顏色更改爲黃色,綠色等effect.Thank你如何在html中動態改變<label>的顏色

+1

看看動畫... –

+0

https://stackoverflow.com/a/27768979/774078這是可能的CSS單獨 –

回答

0

如何使用CSS3動畫。我從W3Schools中獲得了這個概念。檢查出來

您可以通過除以百分比來添加更多的背景顏色。

label { 
 

 
    background-color: red; 
 

 
    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */ 
 
    -webkit-animation-duration: 1s; /* Safari 4.0 - 8.0 */ 
 
    -webkit-animation-delay: 1s; /* Safari 4.0 - 8.0 */ 
 
    animation-name: example; 
 
    animation-duration: 1s; 
 
    animation-delay: 1s; 
 
    animation-iteration-count: infinite; 
 
} 
 

 
/* Safari 4.0 - 8.0 */ 
 
@-webkit-keyframes example { 
 
    0% {background-color:red; } 
 
    25% {background-color:yellow; } 
 
    50% {background-color:blue; } 
 
    75% {background-color:green; } 
 
    100% {background-color:red; } 
 
} 
 

 
/* Standard syntax */ 
 
@keyframes example { 
 
    0% {background-color:red; ;} 
 
    25% {background-color:yellow; } 
 
    50% {background-color:blue;} 
 
    75% {background-color:green; } 
 
    100% {background-color:red; } 
 
}
<label>Mylabel</label>

+0

感謝這偉大的工作 –

+0

不要忘記將其標記爲已接受。在投票按鈕下方。 –

3

animation能做到這一點:

label { 
 
    animation:colorchg 2s infinite; 
 
    color:green 
 
} 
 
@keyframes colorchg { 
 
    50% { 
 
    color:red; 
 
    } 
 
}
<label>color</label>

+0

由於它的工作很大 –

0

我會建議在CSS中這樣做,但如果你想有一個JS的解決方案,您使用setInterval()定義的時間間隔和切換的一類,它指定顏色或者只是改變element.style.color或什麼的,並使用CSS轉換來轉換顏色更改。

var interval = setInterval(function() { 
 
    label.classList.toggle('color'); 
 
},2000)
label { 
 
    transition: 2s; 
 
    color: green; 
 
} 
 
.color { 
 
    color: red; 
 
}
<label id="label">text</label>