当前位置:首页 > 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));
  });
});

表格性能优化

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

h5 实现table

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

标签: table
分享给朋友:

相关文章

react的table如何隐藏列

react的table如何隐藏列

隐藏列的实现方法 在React中隐藏表格列可以通过多种方式实现,以下是几种常见的方法: 动态渲染列 通过条件判断决定是否渲染特定列。在渲染表格时,根据状态或属性过滤掉需要隐藏的列。 const c…

实现vue table

实现vue table

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

vue 实现table切换

vue 实现table切换

Vue 实现 Table 切换的方法 使用 v-if 或 v-show 切换不同表格 通过条件渲染指令 v-if 或 v-show 可以快速切换不同的表格组件。v-if 是惰性的,适合切换频率低的场景…

vue怎么实现table切换

vue怎么实现table切换

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

Vue中table实现CheckBox

Vue中table实现CheckBox

Vue中实现Table的CheckBox功能 在Vue中为表格添加CheckBox功能,可以通过以下方式实现。这里以Element UI的el-table为例,原生表格的实现逻辑类似。 基础实现 定…