跳到內容
調色盤星雲光譜
選擇版面配色

即時套用,保留目前的亮暗模式。

Select (am-select)

am-select 讓使用者從固定選項中選擇一項,適合簡單的檢視切換。它由按鈕與 listbox 組成。需要原生表單提交、必填驗證或行動裝置原生選擇器時,優先使用原生 <select>

先依安裝指南 引入 tokens 與元件樣式。以下程式碼與實際預覽使用同一份 Astro 檔案,包含 import 與讀取選擇結果的腳本。

專案類型單選

互動預覽

選擇一個項目,觀察目前值;停用項目無法選取。

尚未選擇專案類型。

查看程式碼可複製完整範例
---
import Select from "@astromer/core/components/Select.astro";
const options = [
{ value: "portfolio", label: "作品集" },
{ value: "dashboard", label: "管理後台" },
{ value: "store", label: "商店(暫不提供)", disabled: true },
];
---
<div data-select-example>
<Select placeholder="選擇專案類型" options={options} />
<p role="status" data-select-result>尚未選擇專案類型。</p>
</div>
<script>
function initializeExamples() {
for (const example of document.querySelectorAll<HTMLElement>("[data-select-example]")) {
if (example.dataset.initialized) continue;
const trigger = example.querySelector<HTMLButtonElement>(".am-select__trigger");
const result = example.querySelector<HTMLElement>("[data-select-result]");
if (!trigger || !result) continue;
example.dataset.initialized = "true";
// Select exposes the chosen value and label on its trigger.
new MutationObserver(() => {
result.textContent = `目前選擇:${trigger.dataset.label}${trigger.dataset.value}`;
}).observe(trigger, { attributes: true, attributeFilter: ["data-value", "data-label"] });
}
}
initializeExamples();
document.addEventListener("astro:page-load", initializeExamples);
</script>
Prop 型別 預設 用途
options { value: string; label: string; disabled?: boolean }[] 必填 可選項目,value 應保持唯一
placeholder string Select… 尚未選取時顯示的提示
class string 未設定 附加到元件容器的 class

目前沒有初始 value、受控 value、整個元件 disabledname prop。若只需要停用特定選項,設定該 option 的 disabled: true

  • 按鈕按下 EnterSpaceArrowDown 開啟選單;焦點移到目前選取項,尚未選取時移到第一個可用項目。
  • 選項中使用 ArrowUpArrowDown 移動,跳過停用項目;EnterSpace 確認。
  • Escape 關閉並將焦點返回觸發按鈕;Tab 移出或在外部點擊也會關閉。
  • 選取狀態以 aria-selected 呈現,觸發按鈕以 aria-expanded 表達展開狀態。

目前值放在 .am-select__triggerdata-valuedata-label,範例使用 MutationObserver 讀取。元件不會發出原生 select 的 change 事件,也不會自動加入 FormData;表單值、驗證與提交由應用程式管理。

目前不支援多選、搜尋、可輸入 combobox、Home/End 或字首搜尋。下拉位置使用 scoped script 與 CSS;CSS Anchor Positioning 與自動翻轉不是現有契約。

查看 Select Playground