我要创建交通灯控制器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>isiqfor</title>
    <link rel="stylesheet" href="style.css">
</head>
<body onload="timer;">

<div id="isiqfor">
    <div class="green"></div>
    <div class="yellow"></div>
    <div class="red"></div>

</div>
    <script src="script.js"></script>
</body>
</html>


CSS代码:

#isiqfor{
    border: 10px solid black;
    padding: 10px 3px;
    width: 50px;
}
#isiqfor>div{
    width:50px;
    height: 50px;
    border-radius: 50%;
    opacity: .3;
}
.green{
    background-color: green;
}
.yellow{
    background-color: yellow;
}
.red{
    background-color: red;
}


和JS文件:

function myFun () {
    // body...
    var green=document.getElementsByClassName("green")[0];
    var red=document.getElementsByClassName("red")[0];
    var yellow=document.getElementsByClassName("yellow")[0];

    green.style.opacity=1;
    setTimeout(function () {
        /* body... */
        green.style.opacity=.3;
        red.style.opacity=.3;
        yellow.style.opacity=1;
    },5000);

    setTimeout(function () {
        /* body... */
        green.style.opacity=.3;
        red.style.opacity=1;
        yellow.style.opacity=.3;
    },7000);

    setTimeout(function () {
        /* body... */
        green.style.opacity=1;
        red.style.opacity=.3;
        yellow.style.opacity=.3;
    },12000);


}

var timer = setInterval(function () {
    /* body... */
    myFun()
},13000);


但是问题是页面加载时必须等待13秒才能开始红绿灯。如何解决此问题?我想要页面加载时绿灯切换。

最佳答案

设置计时器后是否尝试过立即拨打myFun的电话?请参阅添加到以下代码底部的myFun调用:

var timer = setInterval(function () {
    /* body... */
    myFun()
},13000);

myFun();//Call 'myFun' straight away...

09-17 08:14