使用简单的vue完成html制作红黄绿灯交互的实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
.yellow{
background-color: yellow;
}
.white{
background-color: white;
}
.light{
width: 150px;
height: 150px;
border-radius: 50%;
margin-left: 200px;
</style>
</head>
<body>
<div id="app">
<p>
<h3>{{name}}</h3>
倒计时:<input type="text" v-model="number"/>秒
</p>
<div class="light" v-bind:class="{red:showRed,green:showGreen,yellow:showYellow,white:showWhite}"></div>
</div>
</body>
<script src="js/vue.js"></script>
<script>
var app =new Vue({
el: '#app',
data:{
name:'红灯',
number:5,
showRed:true,
showGreen:false,
showYellow:false,
showWhite:false,
count:0
},
methods:{
start(){
if(this.number==1&&this.showRed){
this.name='黄灯';
this.showRed=false;
this.showGreen=false;
this.showYellow=true;
}else if(this.number==1&&this.showYellow){
this.name='绿灯';
this.showRed=false;
this.showGreen=true;
this.showYellow=false;
}else if(this.number==1&&this.showGreen){
this.name='红灯';
this.showRed=true;
this.showGreen=false;
this.showYellow=false;
}
if(this.number-1>0){
this.number--;
}else{
if(this.showYellow){
this.number=3;
}else{
this.number=5;
}
}
this.count++;
if(this.count%2==0){
this.showWhite=true;
}else{
this.showWhite=false;
}
/* int 防止越界*/
if(this.count>10000){
this.count=0;
}
}
},
created() {
setInterval(this.start,1000);
}
})
</script>
</html>
最终实现效果