阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > <th>-表头单元格

<th>-表头单元格

作者:陈川 阅读数:44616人阅读 分类: HTML

<th>标签的基本概念

<th>标签用于定义HTML表格中的表头单元格,是"table header"的缩写。与普通的<td>单元格不同,<th>元素默认具有加粗和居中的文本样式,语义上表示该单元格是列或行的标题。

<table>
  <tr>
    <th>姓名</th>
    <th>年龄</th>
    <th>职业</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>28</td>
    <td>工程师</td>
  </tr>
</table>

<th>标签的属性

<th>标签支持多种属性来增强功能:

  1. colspan - 横跨多列
<th colspan="2">个人信息</th>
  1. rowspan - 纵跨多行
<th rowspan="3">季度</th>
  1. scope - 定义关联范围
<th scope="col">价格</th>
<th scope="row">产品A</th>
  1. headers - 关联其他表头
<th id="name">姓名</th>
<td headers="name">李四</td>

<th><td>的区别

特性 <th> <td>
默认样式 加粗居中 常规左对齐
语义含义 表头 数据单元格
屏幕阅读器 识别为标题 识别为数据
<table>
  <tr>
    <th>项目</th>
    <th>数量</th>
  </tr>
  <tr>
    <td>苹果</td>
    <td>5</td>
  </tr>
</table>

样式定制示例

虽然<th>有默认样式,但可以通过CSS完全自定义:

th {
  background-color: #4CAF50;
  color: white;
  padding: 15px;
  text-align: left;
  border-bottom: 2px solid #ddd;
}

th:hover {
  background-color: #45a049;
}

响应式表格中的<th>

在小屏幕设备上,可以通过CSS将表格转换为卡片布局:

@media screen and (max-width: 600px) {
  table, thead, tbody, th, td, tr {
    display: block;
  }
  
  th {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  
  td:before {
    content: attr(data-th);
    font-weight: bold;
    display: inline-block;
    width: 120px;
  }
}

可访问性实践

为增强可访问性,建议:

  1. 始终使用scope属性
  2. 为复杂表格添加<caption>
  3. 使用aria-describedby关联描述
<table aria-describedby="table-desc">
  <caption>2023年销售数据</caption>
  <tr>
    <th scope="col" id="product">产品</th>
    <th scope="col" id="sales">销量</th>
  </tr>
  <tr>
    <td headers="product">A</td>
    <td headers="sales">1200</td>
  </tr>
</table>
<p id="table-desc">单位:件</p>

动态生成表头

JavaScript动态创建表头的示例:

const data = [
  { id: 1, name: '商品A', price: 100 },
  { id: 2, name: '商品B', price: 200 }
];

function createTable(data) {
  const table = document.createElement('table');
  const thead = document.createElement('thead');
  const headerRow = document.createElement('tr');
  
  // 获取第一个对象的属性作为表头
  Object.keys(data[0]).forEach(key => {
    const th = document.createElement('th');
    th.textContent = key;
    headerRow.appendChild(th);
  });
  
  thead.appendChild(headerRow);
  table.appendChild(thead);
  
  // 添加数据行...
  document.body.appendChild(table);
}

表头分组

对于复杂表格,可以使用<thead><tfoot><tbody>分组:

<table>
  <thead>
    <tr>
      <th colspan="3">2023年度报告</th>
    </tr>
    <tr>
      <th>季度</th>
      <th>收入</th>
      <th>支出</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Q1</td>
      <td>10000</td>
      <td>8000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>总计</th>
      <td>40000</td>
      <td>32000</td>
    </tr>
  </tfoot>
</table>

表头排序功能

实现点击表头排序的完整示例:

<table id="sortable-table">
  <thead>
    <tr>
      <th onclick="sortTable(0)">姓名 ↑↓</th>
      <th onclick="sortTable(1)">年龄 ↑↓</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>张三</td><td>25</td></tr>
    <tr><td>李四</td><td>30</td></tr>
  </tbody>
</table>

<script>
function sortTable(columnIndex) {
  const table = document.getElementById('sortable-table');
  const rows = Array.from(table.querySelectorAll('tbody tr'));
  const isAsc = table.querySelector(`th:nth-child(${columnIndex+1})`).classList.toggle('asc');
  
  rows.sort((a, b) => {
    const aVal = a.cells[columnIndex].textContent;
    const bVal = b.cells[columnIndex].textContent;
    return isAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
  });
  
  table.tBodies[0].append(...rows);
}
</script>

<style>
th.asc::after { content: ' ↑'; }
th:not(.asc)::after { content: ' ↓'; }
th { cursor: pointer; }
</style>

表头固定实现

CSS实现表头固定的方法:

.table-container {
  height: 300px;
  overflow: auto;
}

table {
  width: 100%;
}

thead th {
  position: sticky;
  top: 0;
  background: white;
  box-shadow: 0 2px 2px -1px rgba(0,0,0,0.4);
}
<div class="table-container">
  <table>
    <thead>
      <tr><th>固定表头1</th><th>固定表头2</th></tr>
    </thead>
    <tbody>
      <!-- 大量数据行 -->
    </tbody>
  </table>
</div>

表头与表单控件结合

表头内包含表单控件的示例:

<table>
  <thead>
    <tr>
      <th>
        <input type="checkbox" id="select-all">
        <label for="select-all">全选</label>
      </th>
      <th>
        <select onchange="filterTable(this.value)">
          <option value="">所有部门</option>
          <option value="IT">IT部</option>
        </select>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox"></td>
      <td>IT部</td>
    </tr>
  </tbody>
</table>

<script>
function filterTable(dept) {
  document.querySelectorAll('tbody tr').forEach(row => {
    row.style.display = !dept || row.cells[1].textContent === dept ? '' : 'none';
  });
}
</script>

表头多行文本处理

处理表头中多行文本的样式方案:

th.multiline {
  white-space: normal;
  word-wrap: break-word;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<table>
  <tr>
    <th class="multiline">这是一个非常<br>长的表头标题<br>需要换行显示</th>
    <th>普通表头</th>
  </tr>
</table>

表头图标集成

在表头中添加图标的几种方式:

  1. 使用字体图标
<th><i class="fas fa-user"></i> 用户</th>
  1. 使用SVG
<th>
  <svg width="16" height="16" viewBox="0 0 24 24">
    <path d="M12 2L1 12h3v9h16v-9h3L12 2z"/>
  </svg>
  主页
</th>
  1. 使用背景图片
th.sortable {
  background-image: url('sort-icon.png');
  background-position: right center;
  background-repeat: no-repeat;
  padding-right: 20px;
}

表头与数据关联

使用data-*属性增强表头与数据的关联:

<table>
  <thead>
    <tr>
      <th data-field="name" data-type="string">姓名</th>
      <th data-field="score" data-type="number">分数</th>
    </tr>
  </thead>
  <tbody>
    <tr data-name="张三" data-score="85"></tr>
  </tbody>
</table>

<script>
document.querySelectorAll('th[data-field]').forEach(th => {
  const field = th.dataset.field;
  const type = th.dataset.type;
  
  th.addEventListener('click', () => {
    // 根据data-type决定排序逻辑
  });
});
</script>

表头工具提示

为表头添加详细说明的工具提示:

<th title="这是详细的说明文字">简略标题</th>

<!-- 或者更复杂的工具提示 -->
<th>
  销售额
  <span class="tooltip">包含所有渠道的销售总额</span>
</th>

<style>
.tooltip {
  visibility: hidden;
  width: 200px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -100px;
  opacity: 0;
  transition: opacity 0.3s;
}

th:hover .tooltip {
  visibility: visible;
  opacity: 1;
}
</style>

表头与打印样式

优化打印时表头显示的CSS:

@media print {
  thead {
    display: table-header-group;
  }
  
  th {
    background-color: #fff !important;
    color: #000 !important;
    border-bottom: 2px solid #000;
  }
  
  table {
    page-break-inside: avoid;
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:-表格行

下一篇:<td>-表格数据单元格

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌