HTML 表格是网页设计中常用的元素,用于展示数据。本教程将深入探讨 HTML 表格的高级特性,包括样式、响应式设计以及交互功能。

表格样式

基本样式

要设置表格的基本样式,可以使用 <style> 标签或者外部 CSS 文件。

<style>
  table {
    width: 100%;
    border-collapse: collapse;
  }
  th, td {
    border: 1px solid black;
    padding: 8px;
    text-align: left;
  }
  th {
    background-color: #f2f2f2;
  }
</style>

高级样式

除了基本样式,还可以使用 CSS3 的伪类和伪元素来增强表格的样式。

<style>
  tr:hover {
    background-color: #f5f5f5;
  }
  td:first-child {
    font-weight: bold;
  }
</style>

响应式表格

响应式表格可以适应不同屏幕尺寸,确保在移动设备上也能良好显示。

<style>
  @media (max-width: 600px) {
    table, thead, tbody, th, td, tr {
      display: block;
    }
    thead tr {
      position: absolute;
      top: -9999px;
      left: -9999px;
    }
    tr { border: 1px solid #ccc; }
    td {
      border: none;
      border-bottom: 1px solid #eee;
      position: relative;
      padding-left: 50%;
    }
    td:before {
      position: absolute;
      top: 6px;
      left: 6px;
      width: 45%;
      padding-right: 10px;
      white-space: nowrap;
      content: attr(data-title);
    }
  }
</style>

表格交互

表格交互可以通过 JavaScript 实现,例如排序、筛选和搜索功能。

<script>
  function sortTable(n) {
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("myTable");
    switching = true;
    dir = "asc";
    while (switching) {
      switching = false;
      rows = table.rows;
      for (i = 1; i < (rows.length - 1); i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
        if (dir == "asc") {
          if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
            shouldSwitch = true;
            break;
          }
        } else if (dir == "desc") {
          if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
            shouldSwitch = true;
            break;
          }
        }
      }
      if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        switchcount++;
      } else {
        if (switchcount == 0 && dir == "asc") {
          dir = "desc";
          switching = true;
        }
      }
    }
  }
</script>

总结

通过本教程,你学到了如何使用 HTML 和 CSS 创建具有高级功能的表格。你可以将这些技能应用到你的项目中,创建更加丰富和交互式的网页。

返回教程列表