2017-05-27 337 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>