<datalist> 元素HTML5 引入 <datalist> 提供原生自動完成功能,無需 JavaScript、無外部依賴、原生支援鍵盤導航、螢幕閱讀器友善。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>輸入框下拉建議 - 原生 datalist</title>
<style>
.search-box { max-width: 400px; margin: 2rem auto; font-family: system-ui; }
.search-label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #333; }
.search-input {
width: 100%; padding: 12px 16px;
font-size: 16px; border: 2px solid #ddd;
border-radius: 8px; box-sizing: border-box;
transition: border-color 0.2s, box-shadow 0.2s;
}
.search-input:focus {
outline: none; border-color: #0066cc;
box-shadow: 0 0 0 3px rgba(0,102,204,0.2);
}
/* 自訂 datalist 下拉樣式(有限支援) */
@-moz-document url-prefix() {
/* Firefox 可調整 option 樣式 */
option { padding: 8px 12px; }
}
</style>
</head>
<body>
<div class="search-box">
<label class="search-label" for="citySearch">搜尋城市</label>
<input type="text" class="search-input" id="citySearch"
list="cities" placeholder="輸入城市名稱..." autocomplete="off">
<datalist id="cities">
<option value="台北市"></option>
<option value="新北市"></option>
<option value="桃園市"></option>
<option value="台中市"></option>
<option value="台南市"></option>
<option value="高雄市"></option>
<option value="基隆市"></option>
<option value="新竹市"></option>
<option value="嘉義市"></option>
<option value="苗栗縣"></option>
<option value="彰化縣"></option>
<option value="南投縣"></option>
<option value="雲林縣"></option>
<option value="屏東縣"></option>
<option value="宜蘭縣"></option>
<option value="花蓮縣"></option>
<option value="台東縣"></option>
<option value="澎湖縣"></option>
<option value="金門縣"></option>
<option value="連江縣"></option>
</datalist>
</div>
</body>
</html>
<input type="text" id="productSearch" list="products" placeholder="搜尋產品...">
<datalist id="products"></datalist>
<script>
const input = document.getElementById('productSearch');
const datalist = document.getElementById('products');
let debounceTimer;
let abortController;
input.addEventListener('input', async e => {
const query = e.target.value.trim();
if (query.length < 2) { datalist.innerHTML = ''; return; }
clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => {
// 取消前一個請求
if (abortController) abortController.abort();
abortController = new AbortController();
try {
const res = await fetch(`/api/products?q=${encodeURIComponent(query)}`, {
signal: abortController.signal
});
const products = await res.json();
// 更新 datalist
datalist.innerHTML = products.map(p =>
``
).join('');
} catch (e) {
if (e.name !== 'AbortError') console.error('搜尋失敗:', e);
}
}, 300);
});
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 選取後取得完整物件(需額外映射)
input.addEventListener('change', () => {
const selected = input.value;
const option = datalist.querySelector(`option[value="${escapeHtml(selected)}"]`);
if (option) {
console.log('選中產品 ID:', option.dataset.id);
// 觸發後續邏輯:導向詳情頁、加入購物車等
}
});
</script>
當 <datalist> 樣式受限、需求複雜(分組、圖片、多欄、鍵盤完整控制)時,建議自行實作:
<style>
.autocomplete { position: relative; max-width: 400px; }
.ac-input { width: 100%; padding: 12px 16px; font-size: 16px; border: 2px solid #ddd; border-radius: 8px; box-sizing: border-box; }
.ac-input:focus { outline: none; border-color: #0066cc; box-shadow: 0 0 0 3px rgba(0,102,204,0.2); }
.ac-dropdown {
position: absolute; top: 100%; left: 0; right: 0;
margin-top: 4px; background: #fff; border: 1px solid #ddd;
border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.12);
max-height: 300px; overflow-y: auto; z-index: 100;
display: none;
}
.ac-dropdown.open { display: block; animation: slideDown 0.15s ease; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }
.ac-group { padding: 8px 0; border-top: 1px solid #eee; }
.ac-group:first-child { border-top: none; }
.ac-group-label { padding: 4px 16px; font-size: 12px; font-weight: 600; color: #888; text-transform: uppercase; }
.ac-item { padding: 10px 16px; cursor: pointer; transition: background 0.1s; display: flex; align-items: center; gap: 12px; }
.ac-item:hover, .ac-item.highlighted { background: #f0f7ff; }
.ac-item-img { width: 32px; height: 32px; border-radius: 4px; object-fit: cover; flex-shrink: 0; }
.ac-item-text { flex: 1; }
.ac-item-name { font-weight: 500; color: #333; }
.ac-item-meta { font-size: 13px; color: #888; }
.ac-empty { padding: 16px; text-align: center; color: #999; }
.ac-loading { padding: 16px; text-align: center; color: #0066cc; }
</style>
<div class="autocomplete">
<input type="text" class="ac-input" id="acInput" placeholder="搜尋產品..." autocomplete="off" aria-autocomplete="list" aria-controls="acList">
<div class="ac-dropdown" id="acList" role="listbox"></div>
</div>
<script>
class Autocomplete {
constructor(inputEl, options = {}) {
this.input = inputEl;
this.dropdown = document.getElementById(options.dropdownId);
this.fetchFn = options.fetchFn;
this.renderItem = options.renderItem;
this.onSelect = options.onSelect;
this.debounce = options.debounce ?? 250;
this.minChars = options.minChars ?? 1;
this.highlightIndex = -1;
this.abortController = null;
this.bindEvents();
}
bindEvents() {
this.input.addEventListener('input', e => this.onInput(e.target.value));
this.input.addEventListener('focus', () => this.onInput(this.input.value));
this.input.addEventListener('keydown', e => this.onKeydown(e));
document.addEventListener('click', e => { if (!this.input.contains(e.target) && !this.dropdown.contains(e.target)) this.close(); });
}
async onInput(value) {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => {
if (value.length < this.minChars) { this.close(); return; }
if (this.abortController) this.abortController.abort();
this.abortController = new AbortController();
this.showLoading();
try {
const data = await this.fetchFn(value, this.abortController.signal);
this.render(data);
this.open();
} catch (e) { if (e.name !== 'AbortError') this.showError(e.message); }
}, this.debounce);
}
render(data) {
if (!data.length) { this.showEmpty(); return; }
this.dropdown.innerHTML = data.map((item, i) =>
`${this.renderItem(item)}`
).join('');
this.highlightIndex = -1;
this.dropdown.querySelectorAll('.ac-item').forEach(el => {
el.addEventListener('click', () => this.select(+el.dataset.index, data));
el.addEventListener('mouseenter', () => this.highlight(+el.dataset.index));
});
}
renderItemDefault(item) {
return `${escapeHtml(item.name)}${item.meta ? `` : ''}`;
}
onKeydown(e) {
const items = this.dropdown.querySelectorAll('.ac-item');
if (!items.length) return;
if (e.key === 'ArrowDown') { e.preventDefault(); this.highlight(Math.min(this.highlightIndex + 1, items.length - 1)); }
else if (e.key === 'ArrowUp') { e.preventDefault(); this.highlight(Math.max(this.highlightIndex - 1, 0)); }
else if (e.key === 'Enter') { e.preventDefault(); if (this.highlightIndex >= 0) this.select(this.highlightIndex); else this.close(); }
else if (e.key === 'Escape') { this.close(); }
}
highlight(index) {
this.dropdown.querySelectorAll('.ac-item').forEach((el, i) => el.classList.toggle('highlighted', i === index));
this.highlightIndex = index;
items[index]?.scrollIntoView({ block: 'nearest' });
}
select(index, data) {
const item = data ? data[index] : this.lastData[index];
this.input.value = item.name || item;
this.close();
this.onSelect?.(item);
}
showLoading() { this.dropdown.innerHTML = '搜尋中…'; this.open(); }
showEmpty() { this.dropdown.innerHTML = '無符合結果'; this.open(); }
showError(msg) { this.dropdown.innerHTML = `錯誤: ${escapeHtml(msg)}`; this.open(); }
open() { this.dropdown.classList.add('open'); }
close() { this.dropdown.classList.remove('open'); this.highlightIndex = -1; }
}
// 使用範例
new Autocomplete(document.getElementById('acInput'), {
dropdownId: 'acList',
minChars: 2,
debounce: 300,
fetchFn: async (query, signal) => {
const res = await fetch(`/api/products?q=${encodeURIComponent(query)}`, { signal });
return res.json(); // [{id, name, sku, image, price, category}, ...]
},
renderItem: item => `
${escapeHtml(item.name)}
`,
onSelect: item => console.log('選中:', item)
});
</script>
| 需求 | 推薦方案 |
|---|---|
| 簡單靜態選項(<50項)、無特殊樣式需求 | <datalist> |
| 動態搜尋、資料量大、需分頁 | 自訂元件 + 虛擬滾動 |
| 需顯示圖片、多欄位、分組標題 | 自訂元件 |
| 需複雜鍵盤操作(Tab 選取、Enter 確認、Esc 關閉) | 自訂元件 |
| 行動裝置原生體驗 | <datalist>(iOS/Android 原生選單) |
| 無障礙合規(WCAG 2.1 AA) | 自訂元件(完整 ARIA)或 <datalist>(原生語意) |
<datalist>:Chrome 20+、Firefox 4+、Edge 12+、Safari 12.1+、Opera 15+::-webkit-calendar-picker-indicator 等偽元素)