萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實作捷運路線指示燈跑馬燈效果

模擬捷運車廂內站名指示燈:綠色光點依序點亮、循環往返。使用 jQuery 操作類別切換,邏輯簡單直觀。

原始版本問題

  • 索引歸零邏輯有誤,導致第二輪不從第一顆開始
  • 使用 `setInterval` 字串參數(`setInterval('fn()', 400)`)屬惡習
  • 未清理計時器,頁面卸載可能記憶體洩漏

修正後的 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>

原生 JS 輕量版(無 jQuery 依賴)

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();

擴充建議

  • 加入站名廣播(Web Speech API `speechSynthesis`)
  • 支援滑鼠懸停顯示完整站名、到站倒數
  • 響應式:行動裝置改為垂直排列
  • 整合真實開放資料(如台北捷運即時到站 API)
copyright © 萬盛學電腦網 all rights reserved