在 HTML 表格中,<td> 元素用于定义表格中的单元格。而scope属性用于指定<th>或<td>元素的作用范围,帮助屏幕阅读器和搜索引擎更好地理解表格的结构。
作用
scope属性可以取以下四个值:
row:指定单元格属于一行。col:指定单元格属于一列。rowgroup:指定单元格属于一行组。colgroup:指定单元格属于一列组。
示例代码
1. row
<table>
<tr>
<th scope="row">Month</th>
<td>January</td>
<td>February</td>
<td>March</td>
</tr>
</table>在这个例子中,scope="row"指定了<th>元素所在的单元格属于一行,帮助屏幕阅读器和搜索引擎更好地理解表格结构。
2. col
// www.javascriptcn.com code example
<table>
<tr>
<th scope="col">Month</th>
<td>January</td>
</tr>
<tr>
<th scope="col">Temperature</th>
<td>10°C</td>
</tr>
</table>在这个例子中,scope="col"指定了<th>元素所在的单元格属于一列,同样帮助提高表格结构的可读性。
3. rowgroup
// www.javascriptcn.com code example
<table>
<tr>
<th scope="rowgroup">Quarterly Report</th>
<td>Q1</td>
<td>Q2</td>
<td>Q3</td>
<td>Q4</td>
</tr>
</table>在这个例子中,scope="rowgroup"指定了<th>元素所在的单元格属于一行组,更好地组织表格数据。
4. colgroup
// www.javascriptcn.com code example
<table>
<tr>
<th scope="colgroup">Sales</th>
<th>Product A</th>
<th>Product B</th>
</tr>
<tr>
<th>Q1</th>
<td>$1000</td>
<td>$1500</td>
</tr>
</table>在这个例子中,scope="colgroup"指定了<th>元素所在的单元格属于一列组,更好地呈现表格结构。
总结
scope属性是一个很有用的属性,能够帮助提高表格的可访问性和可读性。合理使用scope属性可以让表格更易于理解和解释,从而提升用户体验。