HTMLとjsでのベーシックなリスト選択の例
自分用のメモです。
表がずれないようにするだけでも、何だか面倒なんですね…
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>最終完成版(列ソート付き)</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
input, button {
padding: 6px;
margin-bottom: 8px;
}
button:disabled {
background-color: #ccc ;
cursor: not-allowed;
}
/* ===== テーブル全体 ===== */
.table-root {
width: 480px;
}
table {
width: 100%;
min-width: 480px;
border-collapse: collapse;
table-layout: fixed;
}
colgroup col:nth-child(1) { width: 80px; }
colgroup col:nth-child(2) { width: 200px; }
colgroup col:nth-child(3) { width: 200px; }
th, td {
border: 1px solid #aaa ;
padding: 6px;
box-sizing: border-box;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
th {
background: #f0f0f0 ;
cursor: pointer;
user-select: none;
}
th.sort-asc::after {
content: " ▲";
}
th.sort-desc::after {
content: " ▼";
}
/* ===== ボディスクロール ===== */
.tbody-wrapper {
max-height: 520px;
overflow-y: scroll; /* 常時表示 */
overflow-x: hidden;
}
tbody tr {
cursor: pointer;
}
tbody tr:hover {
background-color: #eef ;
}
tbody tr.selected {
background-color: #bcd !important;
}
/* ===== モーダル ===== */
.modal {
display: none;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.4);
justify-content: center;
align-items: center;
}
.modal-content {
background: #fff ;
padding: 20px;
width: 300px;
border-radius: 4px;
}
.close {
float: right;
cursor: pointer;
}
</style>
</head>
<body>
<h2>最終完成版(列ソート付き)</h2>
<input id="filterInput" placeholder="名前で検索">
<button id="searchBtn">検索</button>
<button id="clearBtn">クリア</button><br>
<button id="showDetailBtn" disabled>詳細を表示</button>
<div class="table-root">
<!-- ヘッダ -->
<table>
<colgroup>
<col><col><col>
</colgroup>
<thead>
<tr>
<th data-index="0" data-type="number">ID</th>
<th data-index="1" data-type="string">名前</th>
<th data-index="2" data-type="string">部署</th>
</tr>
</thead>
</table>
<!-- ボディ -->
<div class="tbody-wrapper" id="tbodyWrapper">
<table>
<colgroup>
<col><col><col>
</colgroup>
<tbody id="tableBody"></tbody>
</table>
</div>
</div>
<!-- モーダル -->
<div class="modal" id="modal">
<div class="modal-content">
<div>
詳細 <span class="close" id="closeModal">×</span>
</div>
<div id="modalBody"></div>
</div>
</div>
<script>
/* ===============================
スクロールバー幅計測
================================ */
function getScrollbarWidth() {
const outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.overflow = "scroll";
outer.style.width = "100px";
document.body.appendChild(outer);
const inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
const width = outer.offsetWidth - inner.offsetWidth;
outer.remove();
return width;
}
/* ===== DOM ===== */
const tbodyWrapper = document.getElementById("tbodyWrapper");
const tableBody = document.getElementById("tableBody");
const filterInput = document.getElementById("filterInput");
const searchBtn = document.getElementById("searchBtn");
const clearBtn = document.getElementById("clearBtn");
const showDetailBtn = document.getElementById("showDetailBtn");
const modal = document.getElementById("modal");
const modalBody = document.getElementById("modalBody");
const closeModal = document.getElementById("closeModal");
/* ===== スクロールバー分横幅拡張 ===== */
tbodyWrapper.style.width =
(document.querySelector(".table-root").clientWidth + getScrollbarWidth()) + "px";
/* ===============================
データ生成(200行)
================================ */
let selectedRow = null;
const departments = ["営業", "開発", "人事", "総務"];
// 初期行順を保存
const originalRows = [];
for (let i = 1; i <= 200; i++) {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${i}</td>
<td>社員${i}</td>
<td>${departments[i % 4]}</td>
`;
tr.onclick = () => selectRow(tr);
tableBody.appendChild(tr);
// ★ 初期順を保持
originalRows.push(tr);
}
function selectRow(tr) {
if (selectedRow) selectedRow.classList.remove("selected");
selectedRow = tr;
tr.classList.add("selected");
showDetailBtn.disabled = false;
}
/* ===============================
検索・クリア
================================ */
const rows = () => Array.from(tableBody.rows);
searchBtn.onclick = () => {
resetSelection();
const filter = filterInput.value.toLowerCase();
rows().forEach(r => {
r.style.display =
r.cells[1].textContent.toLowerCase().includes(filter) ? "" : "none";
});
};
clearBtn.onclick = () => {
filterInput.value = "";
rows().forEach(r => r.style.display = "");
// === ソートを初期状態に戻す ===
originalRows.forEach(r => tableBody.appendChild(r));
// ソート状態リセット
sortState.index = null;
sortState.asc = true;
// ソートアイコン削除
document.querySelectorAll("thead th")
.forEach(th => th.classList.remove("sort-asc", "sort-desc"));
resetSelection();
};
/* ===============================
列ソート
================================ */
let sortState = { index: null, asc: true };
document.querySelectorAll("thead th").forEach(th => {
th.addEventListener("click", () => {
const index = Number(th.dataset.index);
const type = th.dataset.type;
// ソート状態切替
sortState.asc = sortState.index === index ? !sortState.asc : true;
sortState.index = index;
// アイコン更新
document.querySelectorAll("th").forEach(t =>
t.classList.remove("sort-asc", "sort-desc")
);
th.classList.add(sortState.asc ? "sort-asc" : "sort-desc");
sortRows(index, type, sortState.asc);
resetSelection();
});
});
function sortRows(index, type, asc) {
const sorted = rows().sort((a, b) => {
let v1 = a.cells[index].textContent;
let v2 = b.cells[index].textContent;
if (type === "number") {
v1 = Number(v1);
v2 = Number(v2);
}
return asc
? v1 > v2 ? 1 : -1
: v1 < v2 ? 1 : -1;
});
sorted.forEach(r => tableBody.appendChild(r));
}
/* ===============================
モーダル
================================ */
showDetailBtn.onclick = () => {
if (!selectedRow) return;
modalBody.innerHTML = `
<p>ID: ${selectedRow.cells[0].textContent}</p>
<p>名前: ${selectedRow.cells[1].textContent}</p>
<p>部署: ${selectedRow.cells[2].textContent}</p>
`;
modal.style.display = "flex";
};
closeModal.onclick = () => modal.style.display = "none";
modal.onclick = e => e.target === modal && (modal.style.display = "none");
function resetSelection() {
if (selectedRow) selectedRow.classList.remove("selected");
selectedRow = null;
showDetailBtn.disabled = true;
}
</script>
</body>
</html>