使用原生 JavaScript 為表格列或清單項目套用斑馬紋與懸停效果,無需 jQuery,輕量且易懂。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>隔行換色範例</title>
<style>
table { border-collapse: collapse; border: 1px solid #999; width: 100%; }
th, td { border: 1px solid #999; padding: 8px; }
.odd { background: #fff; } /* 單行 */
.even { background: #eee; } /* 雙行 */
.hover { background: #ccc; } /* 懸停 */
</style>
</head>
<body>
<table>
<tr><td>列 1</td></tr>
<tr><td>列 2</td></tr>
<tr><td>列 3</td></tr>
<tr><td>列 4</td></tr>
</table>
<ul id="list">
<li>項目 1</li>
<li>項目 2</li>
<li>項目 3</li>
<li>項目 4</li>
</ul>
<script>
// 表格隔行換色
document.addEventListener("DOMContentLoaded", function() {
var rows = document.querySelectorAll("table tr");
rows.forEach(function(tr, i) {
tr.className = (i % 2 === 0) ? "odd" : "even";
tr.addEventListener("mouseenter", function() { this.classList.add("hover"); });
tr.addEventListener("mouseleave", function() { this.classList.remove("hover"); });
});
// 清單隔行換色
var items = document.getElementById("list").getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
items[i].className = (i % 2 === 0) ? "odd" : "even";
items[i].onmouseover = function() { this.classList.add("hover"); };
items[i].onmouseout = function() { this.classList.remove("hover"); };
}
});
</script>
</body>
</html>
DOMContentLoaded 確保 DOM 就緒再操作。classList.add/remove 管理多重類別,不覆蓋原有類別。tr:nth-child(odd/even) 純樣式實現,JS 僅處理懸停;清單同理可用 li:nth-child()。/* 純 CSS 斑馬紋 + 懸停 */
tr:nth-child(odd) { background: #fff; }
tr:nth-child(even) { background: #eee; }
tr:hover, li:hover { background: #ccc; }
現代瀏覽器全支援 :nth-child 與 :hover,純 CSS 方案效能最佳、無 JS 依賴、易維護。僅在極舊環境(IE8-)需 JS 兼容。