實現一組互斥的按鈕選單:點擊任一按鈕時,該按鈕進入「選中」狀態(藍色邊框),其餘按鈕恢復預設狀態(灰色邊框)。適用於篩選器、標籤頁、視圖模式切換等場景。
<div class="btn-group" role="group" aria-label="數據指標選擇">
<button type="button" class="btn" data-metric="inc_call" aria-pressed="true">呼入次數</button>
<button type="button" class="btn" data-metric="inc_conn_call" aria-pressed="false">通話次數</button>
<button type="button" class="btn" data-metric="rate" aria-pressed="false">人工接聽率</button>
<button type="button" class="btn" data-metric="inc_conn_call_20s" aria-pressed="false">20秒接聽率</button>
<button type="button" class="btn" data-metric="inc_wait_duration" aria-pressed="false">等待均長</button>
</div>
.btn-group { display: inline-flex; gap: 4px; font-family: system-ui, sans-serif; }
.btn {
padding: 8px 16px; font-size: 14px; font-weight: 500;
color: #333; background: #fff; border: 1px solid #ddd; border-radius: 4px;
cursor: pointer; transition: all 0.15s ease;
white-space: nowrap;
}
.btn:hover { border-color: #3498db; color: #3498db; }
.btn:focus { outline: none; box-shadow: 0 0 0 3px rgba(52,152,219,0.3); }
.btn[aria-pressed="true"] {
border-color: #3498db; background: #e8f4fd; color: #3498db;
box-shadow: inset 0 1px 3px rgba(52,152,219,0.2);
}
.btn:active:not([aria-pressed="true"]) { background: #f5f5f5; }
(function($) {
$.fn.btnGroup = function(options) {
const settings = $.extend({
selector: "button",
activeAttr: "aria-pressed",
activeClass: "active", // 可選:額外 class
onChange: $.noop // 回調: function(value, $btn, $group)
}, options);
return this.each(function() {
const $group = $(this);
const $buttons = $group.find(settings.selector);
// 初始化:確保只有一個按鈕為 pressed
let $initActive = $buttons.filter(`[${settings.activeAttr}="true"]`);
if ($initActive.length > 1) {
$initActive.slice(1).attr(settings.activeAttr, "false");
} else if ($initActive.length === 0) {
$buttons.first().attr(settings.activeAttr, "true");
}
$group.on("click.btnGroup", settings.selector, function(e) {
const $btn = $(this);
const value = $btn.data("metric") || $btn.val() || $btn.text();
// 已選中則不處理 (或可選:允許取消選中)
if ($btn.attr(settings.activeAttr) === "true") return;
// 更新狀態
$buttons.attr(settings.activeAttr, "false").removeClass(settings.activeClass);
$btn.attr(settings.activeAttr, "true").addClass(settings.activeClass);
// 觸發回調
settings.onChange.call($group[0], value, $btn, $group);
});
// 鍵盤支援:左右鍵切換
$group.on("keydown.btnGroup", settings.selector, function(e) {
const $btn = $(this);
const index = $buttons.index($btn);
let targetIndex = index;
if (e.key === "ArrowRight") targetIndex = (index + 1) % $buttons.length;
else if (e.key === "ArrowLeft") targetIndex = (index - 1 + $buttons.length) % $buttons.length;
else if (e.key === "Home") targetIndex = 0;
else if (e.key === "End") targetIndex = $buttons.length - 1;
else return;
e.preventDefault();
$buttons.eq(targetIndex).focus().click();
});
});
};
})(jQuery);
// 使用
$(function() {
$(".btn-group").btnGroup({
onChange: function(metric, $btn) {
console.log("切換指標:", metric);
// 觸發圖表更新、API 請求等
loadChartData(metric);
}
});
});
class ButtonGroup {
constructor(container, options = {}) {
this.container = typeof container === "string"
? document.querySelector(container) : container;
if (!this.container) return;
this.options = Object.assign({
selector: "button",
activeAttr: "aria-pressed",
onChange: null
}, options);
this.buttons = Array.from(this.container.querySelectorAll(this.options.selector));
this.init();
}
init() {
// 確保單一選中
const pressed = this.buttons.filter(b => b.getAttribute(this.options.activeAttr) === "true");
if (pressed.length > 1) pressed.slice(1).forEach(b => b.setAttribute(this.options.activeAttr, "false"));
else if (pressed.length === 0) this.buttons[0]?.setAttribute(this.options.activeAttr, "true");
// 事件委派
this.container.addEventListener("click", (e) => {
const btn = e.target.closest(this.options.selector);
if (!btn || !this.container.contains(btn)) return;
this.select(btn);
});
// 鍵盤導航
this.container.addEventListener("keydown", (e) => {
const btn = e.target.closest(this.options.selector);
if (!btn) return;
const index = this.buttons.indexOf(btn);
let targetIndex = index;
if (e.key === "ArrowRight") targetIndex = (index + 1) % this.buttons.length;
else if (e.key === "ArrowLeft") targetIndex = (index - 1 + this.buttons.length) % this.buttons.length;
else if (e.key === "Home") targetIndex = 0;
else if (e.key === "End") targetIndex = this.buttons.length - 1;
else return;
e.preventDefault();
this.buttons[targetIndex].focus();
this.select(this.buttons[targetIndex]);
});
}
select(btn) {
if (btn.getAttribute(this.options.activeAttr) === "true") return;
this.buttons.forEach(b => {
b.setAttribute(this.options.activeAttr, "false");
b.classList.remove("active");
});
btn.setAttribute(this.options.activeAttr, "true");
btn.classList.add("active");
const value = btn.dataset.metric || btn.value || btn.textContent;
if (this.options.onChange) this.options.onChange(value, btn, this.container);
}
// 公開方法:程式化切換
setValue(value) {
const btn = this.buttons.find(b =>
b.dataset.metric === value || b.value === value || b.textContent === value
);
if (btn) this.select(btn);
}
getValue() {
const btn = this.buttons.find(b => b.getAttribute(this.options.activeAttr) === "true");
return btn ? (btn.dataset.metric || btn.value || btn.textContent) : null;
}
}
// 使用
document.addEventListener("DOMContentLoaded", () => {
const group = new ButtonGroup(".btn-group", {
onChange: (metric) => loadChartData(metric)
});
// 程式化控制範例
// group.setValue("rate");
// console.log(group.getValue());
});
// 選項:multiple: true
// HTML:
// CSS: .btn[aria-pressed="true"] { ... } (同單選)
// JS 邏輯修改:
// - 移除「取消其他選中」邏輯
// - 切換單個按鈕的 aria-pressed
// - onChange 回傳陣列: selectedValues = buttons.filter(...).map(...)
| 準則 | 實作 |
|---|---|
| Role | 容器 role="group"、按鈕 role="button" (原生 button 自帶) |
| 狀態 | aria-pressed="true/false" 表示按鈕按下狀態 |
| 標籤 | 容器 aria-label 或 aria-labelledby 描述群組用途 |
| 鍵盤 | Tab 進入群組、←→ 在按鈕間移動、Enter/Space 切換、Home/End 首尾 |
| 焦點指示 | :focus-visible 明確焦點環 |
按鈕組切換是 UI 基礎元件,核心在於狀態單一真實來源 (aria-pressed) 與視覺/語意同步。現代開發建議:
<button> 而非 <input type="button"> (語意、無障礙、樣式彈性更好)aria-pressed 作為狀態權威,CSS 選擇器 [aria-pressed="true"] 同步視覺setValue/getValue 程式化介面