请用js编写一个红绿灯程序

以下是一个简单的红绿灯程序,使用HTML、CSS和JavaScript编写。这个程序将模拟一个红绿灯的运作,红灯亮时表示停止,绿灯亮时表示通过。

HTML部分(创建一个包含红绿灯的简单页面):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>红绿灯模拟</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="trafficLight">
        <div class="light red"></div>
        <div class="light yellow"></div>
        <div class="light green"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS部分(为红绿灯添加样式):

#trafficLight {
    width: 150px;
    height: 400px;
    margin: 50px auto;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.light {
    width: 100px;
    height: 100px;
    margin: 10px;
    border-radius: 50%;
    opacity: 0.3;
    transition: opacity 0.5s;
}

.red {
    background-color: red;
}

.yellow {
    background-color: yellow;
}

.green {
    background-color: green;
}

.light.active {
    opacity: 1;
}

JavaScript部分(控制红绿灯的亮灭):

const lights = document.querySelectorAll('.light');
let currentIndex = 0;
const colors = ['red', 'yellow', 'green'];

function changeLight() {
    lights.forEach((light, index) => {
        if (index === currentIndex) {
            light.classList.add('active');
        } else {
            light.classList.remove('active');
        }
    });
    currentIndex = (currentIndex + 1) % lights.length;
}

// 设置红绿灯变化的间隔时间(例如,每3秒变化一次)
setInterval(changeLight, 3000);

这个程序将创建一个包含红、黄、绿三个灯泡的红绿灯。每个灯泡初始时都是半透明的,当它被激活时会变成不透明的。JavaScript代码使用setInterval函数每3秒调用一次changeLight函数,以模拟红绿灯的变化。你可以根据需要调整这个间隔时间。

posted @ 2025-01-16 09:44  王铁柱6  阅读(111)  评论(0)    收藏  举报