儲存格(`
<!DOCTYPE html>
<html>
<head>
<script>
function alignCell() {
document.getElementById('td1').align = "right"; // 靠右對齊
}
</script>
</head>
<body>
<table border="1">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td id="td1">Peter</td>
<td id="td2">Griffin</td>
</tr>
</table>
<br>
<input type="button" onclick="alignCell()" value="Align cell" />
</body>
</html>
| 值 | 說明 |
|---|---|
left | 靠左(預設) |
center | 置中 |
right | 靠右 |
justify | 左右對齊(文字較長時生效) |
char | 依指定字元對齊(鮮少使用) |
/* CSS */
td.align-left { text-align: left; }
td.align-center { text-align: center; }
td.align-right { text-align: right; }
// JS 切換
document.getElementById('td1').className = 'align-right';
<style>
td { padding: 10px; border: 1px solid #ccc; min-width: 100px; }
.align-left { text-align: left; }
.align-center { text-align: center; }
.align-right { text-align: right; }
</style>
<table id="demo2">
<tr><th>Name</th><td id="td1">Peter</td></tr>
</table>
<button onclick="setAlign('left')">左</button>
<button onclick="setAlign('center')">中</button>
<button onclick="setAlign('right')">右</button>
<script>
function setAlign(val) {
document.getElementById('td1').className = 'align-' + val;
}
</script>