模擬捷運車廂內站名指示燈:綠色光點依序點亮、循環往返。使用 jQuery 操作類別切換,邏輯簡單直觀。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 捷運指示燈</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.metro { display:flex; align-items:center; gap:12px; padding:20px; font-family:sans-serif; }
.track { height:4px; background:#ddd; flex:1; position:relative; }
.track::before { content:''; position:absolute; top:50%; left:0; right:0; height:2px; background:#4caf50; transform:translateY(-50%); }
.station { width:24px; height:24px; border-radius:50%; background:#ccc; border:3px solid transparent; transition:all 0.3s; cursor:default; }
.station.active { background:#4caf50; border-color:#4caf50; box-shadow:0 0 12px #4caf50; }
.station::after { content:attr(data-name); position:absolute; top:-28px; left:50%; transform:translateX(-50%); white-space:nowrap; font-size:12px; color:#666; opacity:0; transition:opacity 0.2s; }
.station.active::after { opacity:1; }
</style>
</head>
<body>
<h2 style="text-align:center">捷運站名指示燈</h2>
<div class="metro">
<div class="track"></div>
<div class="stations" id="stations"></div>
<div class="track"></div>
</div>
<script>
$(function() {
var names = ['台北車站','台北橋','三重','先嗇宮','頭前庄','新莊','輔大','丹鳳','迴龍','山佳','新埔','板橋'];
var $container = $('#stations');
var index = 0;
var direction = 1; // 1: forward, -1: backward
var timer;
// 建立站點元素
names.forEach(function(name, i) {
$('' + (i+1) + '').appendTo($container);
});
var $stations = $('.station');
function step() {
$stations.removeClass('active').eq(index).addClass('active');
index += direction;
if (index === names.length - 1 && direction === 1) direction = -1;
else if (index === 0 && direction === -1) direction = 1;
}
timer = setInterval(step, 800);
step(); // 立即顯示第一站
// 頁面卸載清理
$(window).on('beforeunload', function() { clearInterval(timer); });
});
</script>
</body>
</html>
const names = ['台北車站','台北橋','三重','先嗇宮','頭前庄','新莊','輔大','丹鳳','迴龍','山佳','新埔','板橋'];
const container = document.getElementById('stations');
let index = 0, dir = 1, timer;
names.forEach((name, i) => {
const el = document.createElement('div');
el.className = 'station';
el.dataset.name = name;
el.textContent = i+1;
container.appendChild(el);
});
const stations = container.querySelectorAll('.station');
function step() {
stations.forEach(s => s.classList.remove('active'));
stations[index].classList.add('active');
index += dir;
if (index === names.length-1 && dir===1) dir = -1;
else if (index === 0 && dir===-1) dir = 1;
}
timer = setInterval(step, 800);
step();