当前位置:首页 > 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 媒体查询实现移动端适配:

h5 实现table

@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 实现动态数据加载:

h5 实现table

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);
}

标签: table
分享给朋友:

相关文章

react实现竖向table

react实现竖向table

实现竖向表格的布局方案 在React中实现竖向表格(即表头在左侧,数据向右展开的布局)可通过CSS布局调整或组件结构重组完成。以下是几种常见方法: 使用CSS Flexbox或Grid布局 通过旋转…

js实现table

js实现table

使用原生JavaScript创建表格 创建HTML表格需要结合DOM操作,以下是基础实现方法: <!DOCTYPE html> <html> <body> <…

实现vue table

实现vue table

使用 Vue 实现表格组件 Vue 提供了多种方式实现表格功能,以下介绍几种常见方法,涵盖基础表格、动态渲染、分页和排序等功能。 基础表格实现 通过 v-for 循环渲染表格数据,适用于静态或…

vue实现table

vue实现table

Vue 实现 Table 的基本方法 使用原生 HTML 表格 通过 Vue 的 v-for 指令动态渲染表格数据,适合简单场景。 <template> <table>…

vue实现table封装

vue实现table封装

封装 Vue Table 组件的基本思路 封装一个可复用的 Vue Table 组件需要考虑灵活性、可配置性和易用性。核心是通过 props 接收数据和配置,通过插槽(slots)提供自定义内容的能力…

vue怎么实现table切换

vue怎么实现table切换

实现 Vue 中表格切换功能 使用动态组件切换表格 通过 Vue 的 component 动态组件实现表格切换,结合 :is 属性绑定当前显示的表格组件。 <template> &…