原生js实现红绿灯效果

背景

winter重学前端课程中的一个问题:如何用JS实现红绿灯?

  • codepen在线演示:https://codepen.io/ytxka/pen/mNzgMB
  • 效果预览:


    image.png

实现步骤:

  1. 静态页面绘制
  2. 实现改变颜色的函数changeColor
  3. 实现延时函数sleep
  4. 增加倒计时函数countDown

源码

  • HTML



    
    
    
    红绿灯
    


  • CSS
.traffic-light-wrap {
    width: 300px;
    height: 100px;
    padding: 1%;
    box-sizing: border-box;
    box-shadow: 5px 5px 10px rgb(180, 179, 179);
}
ul {
    display: flex;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    justify-content: space-around;
    list-style: none;
}
li {
    width: 80px;
    height: 80px;
    font-size: 18px;
    font-weight: 800;
    text-align: center;
    color: #fff;
    line-height: 80px;
    border-radius: 50%;
    background: #eee;
}
  • JS
var lights = document.getElementById('lights');
var red = document.getElementById('red');
var yellow = document.getElementById('yellow');
var green = document.getElementById('green');

const COLOR_OFF = '#eee';

// 延时
function sleep(wait) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, wait);
    });
}

function initColor(light) {
    light.style.background = COLOR_OFF;
}

// 倒计时
function countDown(ele, time) {
    clearInterval(this.timer);
    let second = time - 1;
    this.timer = setInterval(() => {
        ele.innerHTML = second;
        second -= 1;
       if(second < 0) {
           ele.innerHTML = '';
           clearInterval(this.timer);
       }
    }, 1000);
}

// 改变某个灯的颜色,并重置其他灯的背景色(async函数返回一个promise对象)
async function changeColor(light, color, duration) {
    light.style.background = color;
    countDown(light, duration / 1000);
    await sleep(duration);
    initColor(light);
}

async function lunchTrafficLight() {
    while(true) {
        // changeColor函数返回的是一个promise对象,因此需要await
        await changeColor(red, '#e85a5a', 5000);
        await changeColor(yellow, '#f7bc69', 3000);
        await changeColor(green, '#61b54a', 5000);
    }
}

lunchTrafficLight();

你可能感兴趣的:(原生js实现红绿灯效果)