h5 实现table
实现 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);
}


