把整列的對齊方式一次改掉,比逐格設定方便得多。下面範例將表頭列改為靠左對齊。
<!DOCTYPE html>
<html>
<head>
<script>
function leftAlign() {
document.getElementById('header').align = "left";
}
</script>
</head>
<body>
<table width="100%" border="1">
<tr id="header">
<th>Firstname</th><th>Lastname</th>
</tr>
<tr>
<td>Peter</td><td>Griffin</td>
</tr>
</table>
<br>
<input type="button" onclick="leftAlign()" value="Left-align table row" />
<p><b>Note:</b> This example does not work in Internet Explorer.</p>
</body>
</html>th 元素在多數瀏覽器的預設樣式中帶有 text-align: center 與 font-weight: bold。這也是範例中原註明「在 IE 中無效」的原因——IE 對 tr 層級 align 屬性的繼承處理與其他瀏覽器不同,設定不一定會傳遞到 th 上。
align 屬性已在 HTML5 中棄用,改用 CSS 不僅跨瀏覽器一致,也能一次解決 th 的預設樣式問題:
var header = document.getElementById('header');
// 直接改樣式
Array.prototype.forEach.call(header.cells, function(cell) {
cell.style.textAlign = "left";
});或更推薦的 class 寫法:
/* CSS:明確覆寫 th 的預設居中 */
#header th { text-align: left; }
/* JS */
document.getElementById('header').classList.add('left-aligned');關鍵在於選擇器要寫成 #header th 而不是 #header。因為 text-align 雖然具繼承性,但瀏覽器樣式表中 th 的 text-align: center 是直接作用在 th 上的宣告,會蓋過從 tr 繼承而來的值。這點與垂直對齊的行為不同,是很多人踩過的坑。
對齊規則最好一次想清楚並集中定義:文字欄靠左、數字欄靠右、狀態標籤居中。把這些做成三個 CSS class,再由資料型別決定要掛哪一個,後續維護會輕我让多。若表格由前端框架產生,也可以直接在元件層套用對應 class,不必回到 DOM 上事後修改。