經典電商風格搜索框:頂部 Tab 切換搜索引擎 (綜合/商品/店鋪/郵件...),輸入框聯想建議,切換記憶用戶上次選擇。純前端實現,無後端依賴。




input[name="engine"] 值。https://s.taobao.com/search?q= + 關鍵詞)。input 事件防抖 → JSONP 跨域請求建議 API (淘寶/百度/Google Suggest) → 渲染下拉列表 → 鍵盤 ↑↓/Enter 選中填入。localStorage.setItem('lastSearchEngine', index),頁面載入恢復。tablist/tab/tabpanel)、鍵盤導航 (Tab/Enter/方向鍵)、焦點管理。class TaobaoSearch {
constructor(root) {
this.root = root;
this.tabs = root.querySelectorAll('.search-tab');
this.input = root.querySelector('.search-input');
this.form = root.querySelector('.search-form');
this.suggestBox = root.querySelector('.suggest-box');
this.engines = [
{ name: '綜合', url: 'https://s.taobao.com/search?q=' },
{ name: '商品', url: 'https://s.taobao.com/search?q=', params: '&tab=all' },
{ name: '店鋪', url: 'https://shopsearch.taobao.com/browse/shop_search.htm?q=' },
{ name: '郵件', url: 'https://mail.qq.com/cgi-bin/search?keyword=' }
];
this.activeIndex = parseInt(localStorage.getItem('lastSearchEngine')) || 0;
this.debounceTimer = null;
this.init();
}
init() {
this.renderTabs();
this.bindEvents();
this.activateTab(this.activeIndex);
}
renderTabs() {
// 動態生成 Tab DOM,綁定 ARIA
}
bindEvents() {
this.tabs.forEach((tab, i) => tab.addEventListener('click', () => this.activateTab(i)));
this.input.addEventListener('input', () => this.debounceSuggest());
this.input.addEventListener('keydown', (e) => this.handleSuggestKeydown(e));
this.form.addEventListener('submit', (e) => this.handleSubmit(e));
document.addEventListener('click', (e) => this.closeSuggest(e));
}
activateTab(index) {
this.activeIndex = index;
this.tabs.forEach((t, i) => t.classList.toggle('active', i === index));
localStorage.setItem('lastSearchEngine', index);
}
debounceSuggest() {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => this.fetchSuggest(), 150);
}
async fetchSuggest() {
const kw = this.input.value.trim();
if (!kw) return this.hideSuggest();
try {
// JSONP 示例 (淘寶建議)
const data = await this.jsonp(`https://suggest.taobao.com/sug?q=${encodeURIComponent(kw)}&code=utf-8`);
this.renderSuggest(data.result); // [{k: '關鍵詞'}, ...]
} catch (e) { console.warn(e); }
}
jsonp(url) {
return new Promise((resolve, reject) => {
const cbName = 'jsonp_' + Date.now();
window[cbName] = (data) => { resolve(data); delete window[cbName]; script.remove(); };
const script = document.createElement('script');
script.src = `${url}&callback=${cbName}`;
script.onerror = reject;
document.head.appendChild(script);
});
}
renderSuggest(items) {
this.suggestBox.innerHTML = items.map((it, i) =>
`${it.k}`
).join('');
this.suggestBox.style.display = 'block';
}
handleSuggestKeydown(e) {
const items = this.suggestBox.querySelectorAll('.suggest-item');
if (!items.length) return;
// ↑↓ 選中、Enter 填入、Esc 關閉
}
handleSubmit(e) {
e.preventDefault();
const kw = this.input.value.trim();
if (!kw) return;
const engine = this.engines[this.activeIndex];
window.open(engine.url + encodeURIComponent(kw) + (engine.params || ''), '_blank');
}
closeSuggest(e) {
if (!this.suggestBox.contains(e.target) && e.target !== this.input) this.suggestBox.style.display = 'none';
}
}
// 初始化
document.addEventListener('DOMContentLoaded', () => {
new TaobaoSearch(document.querySelector('.taobao-search'));
});
.taobao-search { position: relative; width: 500px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto; }
.search-tabs { display: flex; border-bottom: 2px solid #ff4400; }
.search-tab { padding: 8px 16px; cursor: pointer; color: #666; font-size: 14px; }
.search-tab.active { color: #ff4400; border-bottom: 2px solid #ff4400; margin-bottom: -2px; }
.search-input { width: 100%; padding: 10px 16px; font-size: 16px; border: 2px solid #ff4400; border-radius: 4px; box-sizing: border-box; }
.suggest-box { position: absolute; top: 100%; left: 0; right: 0; background: #fff; border: 1px solid #ddd; border-top: none; border-radius: 0 0 4px 4px; box-shadow: 0 4px 8px rgba(0,0,0,.1); z-index: 100; display: none; }
.suggest-item { padding: 8px 16px; cursor: pointer; }
.suggest-item:hover, .suggest-item.selected { background: #f5f5f5; }
fetch + CORS 代替 JSONP (需後端支援)。IntersectionObserver 延遲初始化 (首屏外不實例化)。x-webkit-speech / Web Speech API。這是一個典型的「看似簡單、細節決定體驗」的前端組件,適合作為面試手寫題或組件庫建設練習。