如何编写代码以动态更改html中元素的颜色。例如:如果 Hello 是标签,从前 2 秒开始,它应该将颜色更改为黄色,然后更改为绿色,依此类推,并具有过渡效果。谢谢
animation
可以做到这一点:
label {
animation:colorchg 2s infinite;
color:green
}
@keyframes colorchg {
50% {
color:red;
}
}
<label>color</label>
使用 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>
我建议在 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>