萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML <tr> 標籤完整屬性指南:表格行語意、對齊、無障礙與樣式控制

基本語法

<table>
  <tr>
    <th>表頭</th>
    <td>資料</td>
  </tr>
</table>

<tr> (Table Row) 僅能作為 <table>、<thead>、<tbody>、<tfoot> 的直接子元素,包含一或多個 <th> 或 <td>。

屬性詳解

屬性說明值狀態
align水平對齊left | center | right | justify | char棄用 (CSS: text-align)
valign垂直對齊top | middle | bottom | baseline棄用 (CSS: vertical-align)
bgcolor背景色顏色值棄用 (CSS: background-color)
char對齊字元 (配合 align=char)單字元棄用
charoff字元偏移量長度棄用
全域屬性id, class, style, data-*, aria-*, tabindex 等--支援
事件屬性onclick, onmouseover 等--支援 (建議用 addEventListener)

現代 CSS 替代方案

<style>
  tr:nth-child(even) { background: #f9f9f9; }   /* 斑馬紋 */
  tr:hover { background: #eef; }               /* 懸停高亮 */
  tr.selected { background: #bde; }            /* 選中狀態 */
  td, th { text-align: left; vertical-align: middle; padding: 8px 12px; }
  /* 邏輯屬性支援 RTL */
  td { text-align: start; }
</style>

無障礙 (a11y) 關鍵點

  • 使用 <th scope="col|row"> 明確表頭範圍
  • <caption> 提供表格標題/摘要
  • 複雜表格加 <thead>/<tbody>/<tfoot> 結構化
  • 避免巢狀表格;改用 CSS Grid 佈局

常見錯誤

  1. 直接在 <tr> 設寬度:無效,寬度由儲存格或 table-layout 決定
  2. 跨行/跨列未正確設定:rowspan/colspan 需在 <td>/<th> 上設定
  3. 省略 <tbody>:瀏覽器會自動補上,但 JS 操作 table.rows 可能包含 thead/tfoot 行

JavaScript 操作常用 API

const row = table.insertRow(index);        // 插入行 (自動建立 td 需手動)
row.insertCell(index);                     // 插入儲存格
row.deleteCell(index);
row.cells;                                 // HTMLCollection of cells
row.rowIndex;                              // 在整個 table 中的索引
row.sectionRowIndex;                       // 在 thead/tbody/tfoot 中的索引
copyright © 萬盛學電腦網 all rights reserved