前几天面试要求用原生js写这个,当时写了,没写完,说了自己的思路,面试官说你已经写了很长时间了,算是没戏了,这么简单的一个题目,现在用能想到的几种方法(css3,js)写下
第一种:函数式(js)
html结构如下
<div id="light" class="green"> </div>
<style type="text/css">
#light{width:200px; height:200px; animation: hld 6s ease infinite}
.green{background: green;}
.yellow{background: yellow;}
.red{background: red;}
</style>
<script type="text/javascript">
function toGreen(){
document.getElementById("light").style.background = 'green';
setTimeout(toYellow,3000)
}
function toYellow(){
document.getElementById("light").style.background = 'yellow';
setTimeout(toRed,1000)
}
function toRed(){
document.getElementById("light").style.background = 'red';
setTimeout(toGreen,2000)
}
toGreen();
</script>
效果如下:
第二种
function hld(light) {
this.light = document.getElementById(light);
}
hld.prototype.turn = function() {
var light = this.light;
(function turnColoe() {
var that = this;
setTimeout(function() {
light.className = 'yellow';
setTimeout(function() {
light.className = 'red';
setTimeout(function() {
light.className = 'green';
setTimeout(turnColoe(), 0);
}, 2000);
}, 1000)
}, 3000)
})()
}
function ele(n) {
var test = new hld(n);
return test;
}
ele('light').turn();
第三种
纯css3 动画animation 写
<style type="text/css">
#light {
width: 200px;
height: 200px;
animation: hld 6s ease infinite
}
@keyFrames hld{
0% {
background: green
}
50%
{
background: yellow
}
67% {
background: red
}
}
</style>
效果如下: