並べ替えテーブルに、三角矢印を付けてみました。
No | 市区町村コード | 区名 | ふりがな | 英語 | 面積 | 人口 |
---|---|---|---|---|---|---|
1 | 14101 | 鶴見区 | つるみく | tsurumi | 33.23 | |
2 | 14102 | 神奈川区 | かながわく | kanagawa | 23.73 | |
3 | 14103 | 西区 | にしく | nishi | 7.03 | |
4 | 14104 | 中区 | なかく | naka | 21.2 | |
5 | 14105 | 南区 | みなみく | minami | 12.65 | |
6 | 14106 | 保土ケ谷区 | ほどがやく | hodogaya | 21.93 | |
7 | 14107 | 磯子区 | いそごく | isogo | 19.05 | |
8 | 14108 | 金沢区 | かなざわく | kanazawa | 30.96 | |
9 | 14109 | 港北区 | こうほくく | kohoku | 31.4 | |
10 | 14110 | 戸塚区 | とつかく | totsuka | 35.79 | |
11 | 14111 | 港南区 | こうなんく | konan | 19.9 | |
12 | 14112 | 旭区 | あさひく | asahi | 32.73 | |
13 | 14113 | 緑区 | みどりく | midori | 25.51 | |
14 | 14114 | 瀬谷区 | せやく | seya | 17.17 | |
15 | 14115 | 栄区 | さかえく | sakae | 18.52 | |
16 | 14116 | 泉区 | いずみく | izumi | 23.58 | |
17 | 14117 | 青葉区 | あおばく | aoba | 35.22 | |
18 | 14118 | 都筑区 | つづきく | tsuzuki | 27.87 | |
(㎡) | (人) |
CSS
table thead th {
cursor: pointer;
position: relative;
}
table thead th::before,
table thead th::after {
content: "";
height: 0;
width: 0;
position: absolute;
border: 4px solid transparent;
right: 1px;
top: 50%;
}
table thead th::before {
border-bottom-color: #aaa;
margin-top: -10px;
}
table thead th::after {
border-top-color: #aaa;
margin-top: 1px;
}
table thead th.asc::before {
border-bottom-color: #444;
}
table thead th.desc::after {
border-top-color: #444;
}
三角形のデザインについては、下記ブログを参考にさせていただきました。
「CSS だけで並び替え矢印 ソートインジケータ を作る – A Memorandum」

CSS だけで並び替え矢印 ソートインジケータ を作る - A Memorandum
はじめに CSS で三角形を作る 準備 ボーダーで正方形を書く ボーダーを広くする ボーダーをさらに広くする 不要なボーダーを消す 2つ目の三角形を作成する 2つの三角形の並びを調整する テーブルを作る ソートインジケータ を付ける クリッ...
JavaScript
'use strict'
window.onload = function () {
document.querySelectorAll('table').forEach(function(table) {
if (table.tHead) {
table.tHead.querySelectorAll('th').forEach(function(th) {
th.classList.toggle('asc');
th.onclick = function(e) {
if (e.target.textContent != 'No') {
e.target.classList.toggle('asc');
e.target.classList.toggle('desc');
}
var cells = new Array();
for (let i = 0; i < table.tBodies[0].rows.length; i++) {
var cell = new Object();
cell.row = table.tBodies[0].rows[i];
cell.key = table.tBodies[0].rows[i].cells[e.target.cellIndex].textContent;
cells.push(cell);
}
if (e.target.classList.contains('desc')) {
cells.sort(desc);
} else {
cells.sort(asc);
}
for (let i = 0; i < cells.length; i++) {
cells[i].row.cells[0].textContent = i + 1;
table.tBodies[0].appendChild(cells[i].row);
}
};
});
}
});
};
function asc(a, b) {
if (a.key == '') return 1;
if (b.key == '') return -1;
if (!isNaN(a.key)) {
if (!isNaN(b.key)) {
return a.key - b.key;
}
}
if (a.key < b.key) return -1;
if (a.key > b.key) return 1;
return 0;
}
function desc(a, b) {
if (a.key == '') return -1;
if (b.key == '') return 1;
if (!isNaN(a.key)) {
if (!isNaN(b.key)) {
return b.key - a.key;
}
}
if (a.key < b.key) return 1;
if (a.key > b.key) return -1;
return 0;
}
HTML
<thead>タグを持たないテーブルについては、並べ替えを行いません。
コメント