使用CSS实现响应式表格列排序功能需要结合JavaScript来实现。具体步骤如下:
首先,在表格头部添加排序按钮,用于触发排序功能。可以使用伪元素或者图标字体来实现。
在CSS中设置表格的样式,包括表格布局、边框、背景色等。同时,为表格头部的排序按钮设置样式,使其在不同状态下呈现不同的样式。
table {
border-collapse: collapse;
width: 100%;
background-color: #fff;
}
th {
background-color: #f2f2f2;
font-weight: bold;
cursor: pointer;
}
th:hover {
background-color: #ddd;
}
th.active {
background-color: #4caf50;
color: #fff;
}
th.active:after {
content: "\25b2";
}
th.desc:after {
content: "\25bc";
}
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "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 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
// 更新排序状态
var ths = table.getElementsByTagName("TH");
for (i = 0; i < ths.length; i++) {
ths[i].classList.remove("active");
ths[i].classList.remove("desc");
}
var th = table.getElementsByTagName("TH")[n];
th.classList.add("active");
if (dir == "desc") {
th.classList.add("desc");
}
}
var ths = document.getElementsByTagName("TH");
for (var i = 0; i < ths.length; i++) {
ths[i].addEventListener("click", function() {
var n = this.cellIndex;
sortTable(n);
});
}
综上所述,使用CSS实现响应式表格列排序功能需要结合JavaScript来实现,主要包括设置表格的样式和排序按钮的样式,以及实现排序功能和事件监听器。