要创建具有可调列的HTML表,您可以使用HTML、CSS和JavaScript来实现。以下是一个简单的示例,展示了如何创建一个可调列的HTML表:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可调列的HTML表</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th onclick="sortTable(0)">姓名</th>
<th onclick="sortTable(1)">年龄</th>
<th onclick="sortTable(2)">城市</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>25</td>
<td>北京</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
<td>上海</td>
</tr>
<tr>
<td>王五</td>
<td>20</td>
<td>广州</td>
</tr>
</tbody>
</table>
<script src="scripts.js"></script>
</body>
</html>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
cursor: pointer;
}
function sortTable(columnIndex) {
const table = document.getElementById("myTable");
let rows, switching, i, x, y, shouldSwitch, direction, switchCount = 0;
switching = true;
direction = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[columnIndex];
y = rows[i + 1].getElementsByTagName("TD")[columnIndex];
if (direction === "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (direction === "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 && direction === "asc") {
direction = "desc";
switching = true;
}
}
}
}
这个示例中,我们创建了一个包含姓名、年龄和城市的简单表格。通过点击表头,可以按照相应的列进行排序。这个示例使用了HTML、CSS和JavaScript来实现可调列的表格。
领取专属 10元无门槛券
手把手带您无忧上云