效果预览
主要思路:
- 首先,我们要写三个div块,分别用来装红绿黄灯,另外写两个button按钮表示开始和暂停
- 接着,写div的css样式,让div变成圆形需要用到border-radius属性,然后为了让三个div块横向排列,这里我们使用float:left属性。
- JS实现:主要使用三个函数:①demo( ) ②start( )③stop( ),
demo函数用来实现三个信号灯的轮播效果,其中主要是利用visibility属性的hidden;start函数利用setInterval(demo,1000)来循环调用demo函数,这里的1000指的是1000毫秒,即1秒钟调用一次;stop函数利用clearInterval来暂停当前动画。
主要代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#d1{
width:100px;
height:100px;
border-radius:70px;
background-color:red;
float: left;
/*display: inline;*/
}
#d2{
width:100px;
height:100px;
border-radius:70px;
background-color:green;
float: left;
/*visibility: hidden;*/
display: inline;
}
#d3{
width:100px;
height:100px;
border-radius:70px;
background-color:yellow;
float: left;
/*visibility: hidden;*/
display: inline;
}
</style>
<script>
var interval;
var j=1;
function demo(){
for(var i=1;i<4;i++){
document.getElementById("d"+i).style.visibility="hidden";
}
document.getElementById("d"+j).style.visibility="visible";
j++;
if(j>3){
j=1;
}
}
function begin(){
interval = setInterval(demo,1000);
}
function stop(){
clearInterval(interval);
}
</script>
</head>
<body>
<div id="d1" style="visibility: hidden;"></div>
<div id="d2" style="visibility: hidden;"></div>
<div id="d3" style="visibility: hidden;"></div>
<button onclick="begin()" style="margin-top: 120px" style="margin-left: 20px;"> start</button>
<button onclick="stop()">stop</button>
</body>
</html>