当前位置:首页 > HTML

h5 实现table

2026-01-15 21:45:37HTML

实现 H5 表格的基本方法

使用 HTML5 的 <table> 标签可以快速创建表格结构。以下是一个基础示例:

<table border="1">
  <thead>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
      <td>25</td>
    </tr>
    <tr>
      <td>李四</td>
      <td>30</td>
    </tr>
  </tbody>
</table>

响应式表格设计

通过 CSS 媒体查询实现移动端适配:

@media screen and (max-width: 600px) {
  table {
    width: 100%;
  }
  td, th {
    display: block;
    width: 100%;
  }
}

表格样式优化

使用 CSS 增强视觉效果:

table {
  width: 100%;
  border-collapse: collapse;
}
th {
  background-color: #f2f2f2;
}
td, th {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}
tr:hover {
  background-color: #f5f5f5;
}

动态表格实现

结合 JavaScript 实现动态数据加载:

function createTable(data) {
  let table = document.createElement('table');
  let thead = table.createTHead();
  let tbody = table.createTBody();

  // 创建表头
  let headerRow = thead.insertRow();
  Object.keys(data[0]).forEach(key => {
    let th = document.createElement('th');
    th.textContent = key;
    headerRow.appendChild(th);
  });

  // 填充数据
  data.forEach(item => {
    let row = tbody.insertRow();
    Object.values(item).forEach(value => {
      let cell = row.insertCell();
      cell.textContent = value;
    });
  });

  return table;
}

表格交互功能

添加排序功能示例:

document.querySelectorAll('th').forEach(th => {
  th.addEventListener('click', () => {
    const table = th.closest('table');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const index = th.cellIndex;

    rows.sort((a, b) => {
      const aText = a.cells[index].textContent;
      const bText = b.cells[index].textContent;
      return aText.localeCompare(bText);
    });

    rows.forEach(row => tbody.appendChild(row));
  });
});

表格性能优化

对于大数据量表格建议使用虚拟滚动技术:

// 使用现有库如 react-window 或自行实现可视区域渲染
function renderVisibleRows(tableHeight, rowHeight, data) {
  const visibleCount = Math.ceil(tableHeight / rowHeight);
  return data.slice(0, visibleCount);
}

h5 实现table

标签: table
分享给朋友:

相关文章

elementui table

elementui table

ElementUI Table 基本用法 ElementUI 的 Table 组件用于展示结构化数据,支持排序、筛选、分页等功能。以下是一个基础示例: <template> &l…

vue实现table

vue实现table

Vue 实现 Table 的基本方法 使用 Vue 实现表格功能可以通过多种方式完成,包括原生 HTML 表格、第三方组件库或自定义组件。以下是几种常见的方法: 原生 HTML 表格 在 Vue 模…