萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

仿淘寶 Tab 切換搜索框實現:多引擎搜索切換、關鍵詞聯想、本地存儲記憶

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

淘寶風格搜索框切換演示
界面結構圖
Tab 狀態切換
聯想下拉效果

核心功能模組

  1. Tab 切換: 點擊/鍵盤切換激活態,更新隱藏 input[name="engine"] 值。
  2. 搜索跳轉: 表單提交時拼接目標引擎 URL (如 https://s.taobao.com/search?q= + 關鍵詞)。
  3. 關鍵詞聯想: input 事件防抖 → JSONP 跨域請求建議 API (淘寶/百度/Google Suggest) → 渲染下拉列表 → 鍵盤 ↑↓/Enter 選中填入。
  4. 狀態持久化: localStorage.setItem('lastSearchEngine', index),頁面載入恢復。
  5. 無障礙支援: ARIA roles (tablist/tab/tabpanel)、鍵盤導航 (Tab/Enter/方向鍵)、焦點管理。

關鍵代碼架構 (Vanilla JS ES6+)

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')); });

CSS 關鍵點 (SCSS 片段)

.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。
  • 單元測試 (Jest + Testing Library) 覆蓋核心邏輯。

這是一個典型的「看似簡單、細節決定體驗」的前端組件,適合作為面試手寫題或組件庫建設練習。

copyright © 萬盛學電腦網 all rights reserved