萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

基於 jQuery 實現自動完成(Autocomplete)輸入框組件

功能需求

  • 用戶輸入時,向後端請求匹配建議。
  • 下拉面板顯示建議列表,支援鍵盤 ↑/↓ 選擇、Enter 確認、滑鼠點選。
  • 關鍵字高亮、點擊頁面其他區域關閉面板。

完整實作代碼

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery Autocomplete Demo</title>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
  <style>
    .autocomplete-wrap { position: relative; display: inline-block; width: 300px; }
    #search-input { width: 100%; padding: 8px 12px; font-size: 14px; box-sizing: border-box; }
    #suggest-box {
      display: none; position: absolute; left: 0; right: 0; top: 100%; margin-top: 2px;
      background: #fff; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,.1);
      max-height: 200px; overflow-y: auto; z-index: 100;
    }
    #suggest-box li { padding: 8px 12px; cursor: pointer; list-style: none; }
    #suggest-box li:hover, #suggest-box li.active { background: #f0f7ff; color: #1890ff; }
    .highlight { background: #fffbe6; padding: 0 2px; border-radius: 2px; }
  </style>
</head>
<body>
  <div class="autocomplete-wrap">
    <input type="text" id="search-input" placeholder="輸入關鍵字搜尋..." autocomplete="off">
    <ul id="suggest-box"></ul>
  </div>

  <script>
  (function ($) {
    $.fn.autocomplete = function (options) {
      const opts = $.extend({
        source: '',           // API URL 或函式 function(query, callback)
        paramName: 'q',       // 請求參數名
        minLength: 1,         // 最小觸發長度
        delay: 300,           // 防抖延遲
        highlight: true,      // 關鍵字高亮
        renderItem: null,     // 自定義渲染 function(item, query) -> html
        onSelect: null        // 選中回調 function(item)
      }, options);

      return this.each(function () {
        const $input = $(this).attr('autocomplete', 'off');
        const $box = $('
    ').hide().insertAfter($input); let requestTimer = null; let currentIndex = -1; let currentData = []; // 關鍵字高亮 function highlight(text, query) { if (!opts.highlight || !query) return text; const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi'); return text.replace(regex, '$1'); } // 顯示建議列表 function showSuggest(data) { currentData = data; currentIndex = -1; $box.empty(); if (!data.length) { $box.hide(); return; } data.forEach((item, i) => { const text = typeof item === 'string' ? item : (item.label || item.value || ''); const html = opts.renderItem ? opts.renderItem(item, $input.val()) : highlight(text, $input.val()); $('
  • ').html(html).data('item', item).appendTo($box); }); $box.show(); $box.children().first().addClass('active'); } // 隱藏 function hideSuggest() { $box.hide(); currentIndex = -1; } // 請求資料 function fetch(query) { if (typeof opts.source === 'function') { opts.source(query, showSuggest); } else if (opts.source) { $.ajax({ url: opts.source, data: { [opts.paramName]: query }, dataType: 'json', success: showSuggest, error: hideSuggest }); } } // 鍵盤導航 $input.on('keydown', function (e) { if (!$box.is(':visible')) return; const $items = $box.children('li'); switch (e.which) { case 38: // Up e.preventDefault(); currentIndex = (currentIndex - 1 + $items.length) % $items.length; break; case 40: // Down e.preventDefault(); currentIndex = (currentIndex + 1) % $items.length; break; case 13: // Enter e.preventDefault(); if (currentIndex >= 0) selectItem($items.eq(currentIndex)); break; case 27: // Esc hideSuggest(); break; } $items.removeClass('active').eq(currentIndex).addClass('active'); }); // 滑鼠點選 $box.on('click', 'li', function () { selectItem($(this)); }); // 輸入防抖請求 $input.on('input', function () { clearTimeout(requestTimer); const query = $(this).val().trim(); if (query.length < opts.minLength) { hideSuggest(); return; } requestTimer = setTimeout(() => fetch(query), opts.delay); }); // 點擊外部關閉 $(document).on('click', function (e) { if (!$(e.target).closest($input.add($box)).length) hideSuggest(); }); function selectItem($li) { const item = $li.data('item'); const text = typeof item === 'string' ? item : (item.label || item.value || ''); $input.val(text); hideSuggest(); if (opts.onSelect) opts.onSelect(item); } }); }; })(jQuery); // 初始化 $('#search-input').autocomplete({ source: '/api/suggest', // 後端返回 ["建議1", "建議2"] 或 [{label, value}, ...] minLength: 1, delay: 200, onSelect: (item) => console.log('Selected:', item) }); </script> </body> </html>

    後端 API 規約範例

    // GET /api/suggest?q=關鍵字
    // 回傳格式 1:字串陣列
    ["蘋果", "蘋果手機", "蘋果筆電"]
    
    // 回傳格式 2:物件陣列(支援顯示值與實際值分離)
    [{"label": "蘋果手機 iPhone 15", "value": "iphone-15"}, {"label": "蘋果筆電 MacBook Pro", "value": "macbook-pro"}]
    

    進階擴展建議

    • 分組顯示:後端返回 {group: '手機', items: [...]},前端渲染分組標題。
    • 異步加載更多:列表底部顯示「載入更多」,滾動到底部追加請求。
    • 快取機制:使用 Map 快取查詢結果,避免重複請求。
    • 無障礙支援:添加 role="listbox"、aria-activedescendant 等 ARIA 屬性。
    copyright © 萬盛學電腦網 all rights reserved