製作表格時,經常需要調整整行文本的水平對齊方式。本文用一個簡潔的例子,演示如何用 JavaScript 讓表格中的整行文本靠左或靠右對齊。
關鍵是拿到目標行後設置其 align 屬性:
<!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>
點擊按鈕後,leftAlign() 會把 id 為 header 的整行 align 設為 "left",使該行文本靠左對齊。align 同樣支持 "right" 和 "center"。需要注意的是,此示例在 Internet Explorer 中可能不生效,實際開發中建議改用 CSS 的 text-align 來實現對齊,兼容性更好。