對於網站和應用程序的開發者來說,表格是展示信息的重要工具。但是,這個工具常常被過度使用,導致信息的展示效果變得複雜混亂。這時候,使用CSS對表格進行優化,可以使得表格更加易讀和易用。
一、選擇適當的顏色
網站中的色彩設計是至關重要的。當處理表格時,顏色的使用可以使信息更加明顯和突出。當您使用RGB顏色時,嘗試使用色調變化來強調錶中最重要的數據。
例如,以下代碼生成表格中交替出現的淺藍和灰色背景:
table tr:nth-child(2n) {
background-color: #f2f2f2;
}
table tr:nth-child(2n+1) {
background-color: #fff;
}
注意,此代碼在使用前需要先確保您的表格具有交替行,以便代碼生效。
此外,您可以詳細了解一些關於顏色設計的基本原則,就可以指導您更好地選擇顏色。
二、懸停效果
表格的懸停效果是對CSS操作的一項基本功能。它可以使您的表格內容更加易讀和易用。
可通過以下代碼實現懸停效果:
table tbody tr:hover {
background-color: #f5f5f5;
}
當您懸停在表格的任意一行上時,此代碼將會將當行高亮。
三、表格排序
當表格包含大量數據時,按照指定的字段排序數據通常很有必要。為了實現這個目標,我們可以基於CSS中JavaScript來編寫代碼。
以下是一種典型的基於JavaScript的表格排序實現方法:
function sortByColumn(table, column, asc = true) {
const dirModifier = asc ? 1 : -1;
const tBody = table.tBodies[0];
const rows = Array.from(tBody.querySelectorAll("tr"));
const sortedRows = rows.sort((a, b) => {
const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
});
while (tBody.firstChild) {
tBody.removeChild(tBody.firstChild);
}
tBody.append(...sortedRows);
table.querySelectorAll("th").forEach(th => th.classList.remove("th-sort-asc", "th-sort-desc"));
table.querySelector(`th:nth-child(${ column + 1 })`).classList.toggle("th-sort-asc", asc);
table.querySelector(`th:nth-child(${ column + 1 })`).classList.toggle("th-sort-desc", !asc);
}
document.querySelectorAll(".sortable thead th").forEach(headerCell => {
headerCell.addEventListener("click", () => {
const tableElement = headerCell.closest(".sortable");
const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell);
const currentIsAscending = headerCell.classList.contains("th-sort-asc");
sortByColumn(tableElement, headerIndex, !currentIsAscending);
});
});
此代碼中重點使用了`table.sorted`、`th-sort-asc`,和`th-sort-desc`類。當您單擊表頭時,JavaScript將重排數據並更新類,以反映升序和降序排序。
四、可摺疊的表格
為了在同一屏幕空間中展示更多信息,具有摺疊表格的網頁或應用程序將會特別有用。
以下是一個簡單的展示如何製作可摺疊表格的代碼樣例:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
button {
background-color: inherit;
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
| 標題 1 | 標題 2 | 標題 3 | 操作 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 數據 1 | 數據 2 | 數據 3 | |||||||||||||
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/183394.html 贊 (0)
打賞
微信掃一掃
支付寶掃一掃
java數組打印,java數組打印一行
上一篇
2024-11-24 16:28
java回滾,java回滾操作
下一篇
2024-11-24 16:29 | |||||||||||||||
微信掃一掃
支付寶掃一掃