<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
table { border-collapse: collapse; width: 70%; margin: 1rem auto; }
th, td { border: 1px solid #ddd; padding: 8px; }
tr.highlight { background: #08246b; color: #fff; }
</style>
</head>
<body>
<table id="dataTable">
<thead><tr><th>ID</th><th>Name</th><th>Age</th></tr></thead>
<tbody>
<tr><td>1</td><td>Alice</td><td>25</td></tr>
<tr><td>2</td><td>Bob</td><td>30</td></tr>
<tr><td>3</td><td>Carol</td><td>28</td></tr>
<tr><td>4</td><td>Dave</td><td>35</td></tr>
<tr><td>5</td><td>Eve</td><td>22</td></tr>
</tbody>
</table>
<script>
const table = document.getElementById('dataTable');
const rows = table.tBodies[0].rows; // 只取 tbody 內的列
let current = -1;
function highlight(index) {
// 移除所有高亮
for (const r of rows) r.classList.remove('highlight');
// 邊界循環
if (index < 0) index = rows.length - 1;
if (index >= rows.length) index = 0;
rows[index].classList.add('highlight');
current = index;
// 可選:滾動到可視區
rows[index].scrollIntoView({ block: 'nearest' });
}
// 鍵盤事件
document.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') { highlight(current + 1); e.preventDefault(); }
else if (e.key === 'ArrowUp') { highlight(current - 1); e.preventDefault(); }
});
// 滑鼠點擊選中
table.addEventListener('click', e => {
const tr = e.target.closest('tr');
if (tr && tr.parentNode === table.tBodies[0]) {
highlight(tr.rowIndex - (table.tHead ? 1 : 0)); // rowIndex 含 thead
}
});
// 初始可選中第一列
// highlight(0);
</script>
</body>
</html>
table.tBodies[0].rows 取得真實資料列集合(HTMLCollection,即時更新)。tr.rowIndex 為在整個 table 中的索引(含 thead),需扣除 thead 行數。e.target.closest('tr') 容許點擊單元格內任意元素均能選中該列。scrollIntoView({block:'nearest'}) 確保鍵盤導航時目標列在可視區內。e.key === 'ArrowDown' 而非 keyCode,符合現代標準。document.all、window.event、srcElement 等 IE 專屬 API。document.getElementById('ice').children[0] 假設第一個 child 是 tbody,結構脆弱。setTimeout 輪詢定位已被 position:fixed 取代。現代實作利用 classList、closest()、scrollIntoView()、標準鍵盤事件,程式碼更健壯、可維護、無瀏覽器相容性包袱。