點擊表格行高亮顯示,同時取消其他行高亮,視覺反饋當前選中行。
// 假設表格行有 id 或通過事件目標獲取
$('#myTable tbody tr').on('click', function() {
// 設置當前行背景色
$(this).css('background-color', '#e5e5e5')
// 兄弟行重置
.siblings().css('background-color', '#ffffff');
});
.table-highlight tbody tr {
transition: background-color 0.2s ease; /* 平滑過渡 */
cursor: pointer;
}
.table-highlight tbody tr.selected {
background-color: #e3f2fd !important; /* Material Design 藍色淺色調 */
}
.table-highlight tbody tr:hover:not(.selected) {
background-color: #f5f5f5; /* 懸停提示 */
}
$('#myTable tbody tr').on('click', function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
// 鍵盤無障礙支持
$('#myTable tbody tr').on('keydown', function(e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
$(this).trigger('click');
}
}).attr('tabindex', '0'); // 使行可聚焦
let lastSelected = null;
$('#myTable tbody tr').on('click', function(e) {
const $row = $(this);
if (e.ctrlKey || e.metaKey) {
// Ctrl+點擊:切換單行
$row.toggleClass('selected');
lastSelected = $row;
} else if (e.shiftKey && lastSelected) {
// Shift+點擊:範圍選中
const rows = $('#myTable tbody tr');
const start = rows.index(lastSelected);
const end = rows.index($row);
const [min, max] = [Math.min(start, end), Math.max(start, end)];
rows.slice(min, max + 1).addClass('selected');
} else {
// 單擊:單選模式
$row.addClass('selected').siblings().removeClass('selected');
lastSelected = $row;
}
});
function getSelectedRowsData() {
return $('#myTable tbody tr.selected').map(function() {
const $row = $(this);
return {
id: $row.data('id') || $row.attr('id'),
cells: $row.find('td').map(function() {
return $(this).text().trim();
}).get()
};
}).get();
}
// 存儲選中行主鍵 IDs
let selectedIds = new Set();
$('#myTable').on('click', 'tbody tr', function() {
const id = $(this).data('id');
if ($(this).hasClass('selected')) {
selectedIds.delete(id);
} else {
selectedIds.add(id);
}
});
// 重新加載數據後恢復選中
function restoreSelection() {
$('#myTable tbody tr').each(function() {
if (selectedIds.has($(this).data('id'))) {
$(this).addClass('selected');
}
});
}
/* 利用 :has() 偽類 (現代瀏覽器) 或 radio hack */
.table-css-only tbody tr {
/* 隱藏單選框 */
}
.table-css-only tbody tr input[type="radio"]:checked + td,
.table-css-only tbody tr:has(input[type="radio"]:checked) {
background-color: #e3f2fd;
}
.selected、.highlight、.active-rowtransition: background-color 0.15s 提升體驗tabindex、鍵盤事件、ARIA 屬性 aria-selected$('#table').on('click', 'tbody tr', ...) 而非逐行綁定