IT

テーブル並べ替え②

並べ替えテーブルに、三角矢印を付けてみました。

No市区町村コード区名ふりがな英語面積人口
114101鶴見区つるみくtsurumi33.23
214102神奈川区かながわくkanagawa23.73
314103西区にしくnishi7.03
414104中区なかくnaka21.2
514105南区みなみくminami12.65
614106保土ケ谷区ほどがやくhodogaya21.93
714107磯子区いそごくisogo19.05
814108金沢区かなざわくkanazawa30.96
914109港北区こうほくくkohoku31.4
1014110戸塚区とつかくtotsuka35.79
1114111港南区こうなんくkonan19.9
1214112旭区あさひくasahi32.73
1314113緑区みどりくmidori25.51
1414114瀬谷区せやくseya17.17
1514115栄区さかえくsakae18.52
1614116泉区いずみくizumi23.58
1714117青葉区あおばくaoba35.22
1814118都筑区つづきくtsuzuki27.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>タグを持たないテーブルについては、並べ替えを行いません。

コメント