我想将标签的颜色从红色更改为绿色,然后使用setTimeout()
在2秒后再次变红。从绿色变为红色后应该停止。这应该在一个循环中发生3次。我该怎么做?
<script>
setTimeout(a(),2000);
function a()
{
var i;
for(i=0;i<=2;i++)
{
if(i%2==0)
{
document.getElementById("s1").style.color="red";
}
else
{
document.getElementById("s1").style.color="green";
}
}
}
</script>
<body onload="a()">
<label id="s1">WELCOME</label>
</body>
答案 0 :(得分:2)
for循环只是立即执行,你只能看到它的最后一个变化,它应该是绿色的。您需要将i
拉出函数,以保持状态,然后使用setTimeout
调用self来更改颜色。
setTimeout(a(),2000);
将立即执行function a
,您需要使用setTimeout(a,2000);
。
的setTimeout(一(),2000);在脚本的头部可以删除,只需在你的body.onload上调用a
,a
它自己会处理剩下的事情。
<script>
var i = 0;
function a() {
var color = (i % 2 === 0) ? 'red' : 'green';
document.getElementById("s1").style.color = color;
++i;
if (i <= 2) {
setTimeout(a, 2000);
}
}
</script>
<body onload="a();">
<label id="s1">WELCOME</label>
</body>
&#13;
答案 1 :(得分:1)
您可以尝试以下内容
<script>
setTimeout(b, 2000);
function a() {
document.getElementById("s1").style.color="red";
}
function b() {
document.getElementById("s1").style.color="green";
setTimeout(a, 2000);
}
</script>
<body onload="a()">
<label id="s1">WELCOME</label>
</body>
答案 2 :(得分:1)
我强烈建议您使用CSS动画而不是JavaScript来执行此操作。在JavaScript中跟踪状态是棘手的 - 在CSS中指定它更容易。额外奖励:你的代码将变得更加混乱。
此特定示例将无限循环,但您可以轻松查找有关如何使用CSS动画的文档。
<style>
@keyframes redgreen {
0%, 50%, 100% { color: red; }
25%, 75% { color: green; }
}
@-webkit-keyframes redgreen {
0%, 50%, 100% { color: red; }
25%, 75% { color: green; }
}
</style>
<label style="animation: 2s redgreen;-webkit-animation: 2s redgreen infinite;">Hey!</label>