透過 `
<!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>
| align 值 | CSS text-align |
|---|---|
| left | left |
| center | center |
| right | right |
| justify | justify |
/* CSS */
tr.align-left td, tr.align-left th { text-align: left; }
tr.align-center td, tr.align-center th { text-align: center; }
tr.align-right td, tr.align-right th { text-align: right; }
// JS 切換
document.getElementById('header').className = 'align-left';
<style>
table { width: 100%; border-collapse: collapse; }
th, td { padding: 8px; border: 1px solid #ddd; }
tr.align-left td, tr.align-left th { text-align: left; }
tr.align-center td, tr.align-center th { text-align: center; }
tr.align-right td, tr.align-right th { text-align: right; }
</style>
<table id="demo3">
<tr id="header"><th>Firstname</th><th>Lastname</th></tr>
<tr><td>Peter</td><td>Griffin</td></tr>
</table>
<button onclick="setRowAlign('left')">左對齊</button>
<button onclick="setRowAlign('center')">置中</button>
<button onclick="setRowAlign('right')">右對齊</button>
<script>
function setRowAlign(val) {
document.getElementById('header').className = 'align-' + val;
}
</script>
雖然 `tr.align` 曾是快速設定列對齊的捷徑,但現代開發請毫不猶豫選擇 CSS 方案。