萬盛學電腦網

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

JavaScript 實現輸入框彈出選擇面板:搜索、分頁、鍵盤導航完整組件

組件功能特性

  • 🎯 點擊/聚焦輸入框彈出面板
  • 🔍 內置搜索過濾 (即時匹配 name 字段)
  • ⌨️ 鍵盤導航 (上下鍵選中、Enter 確認、Esc 關閉)
  • 🖱️ 鼠標懸停/點擊選擇
  • 📦 支持追加模式 / 替換模式
  • 🎨 遮罩層防止背景交互
  • 🧹 清空/關閉按鈕

核心數據結構

var dataSource = [
    {id: '1', name: '張三'},
    {id: '2', name: '李四'},
    {id: '3', name: '王五'},
    // ... 更多項目
];

完整組件實現 (原生 JS,無依賴)

var SelectPanel = (function() {
    var currentInput = null;
    var currentData = [];
    var selectedIndex = -1;
    var panel = null, mask = null, searchInput = null, listContainer = null;
    
    function createPanel() {
        if (panel) return;
        
        // 遮罩層
        mask = document.createElement('div');
        mask.className = 'select-panel-mask';
        mask.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.3);z-index:9998;display:none;';
        document.body.appendChild(mask);
        
        // 面板容器
        panel = document.createElement('div');
        panel.className = 'select-panel';
        panel.style.cssText = 'position:fixed;width:400px;max-height:300px;background:#fff;border:1px solid #ddd;box-shadow:0 2px 10px rgba(0,0,0,0.2);z-index:9999;display:none;overflow:hidden;';
        panel.innerHTML = 
            '
' + ' ' + '
' + ' ' + ' ' + '
' + '
' + '
'; document.body.appendChild(panel); searchInput = panel.querySelector('.panel-search'); listContainer = panel.querySelector('.panel-list'); // 事件綁定 bindEvents(); } function bindEvents() { // 搜索過濾 searchInput.addEventListener('input', function() { renderList(this.value.trim().toLowerCase()); }); // 鍵盤導航 searchInput.addEventListener('keydown', function(e) { if (e.key === 'ArrowDown') { e.preventDefault(); navigate(1); } else if (e.key === 'ArrowUp') { e.preventDefault(); navigate(-1); } else if (e.key === 'Enter') { e.preventDefault(); confirmSelection(); } else if (e.key === 'Escape') { close(); } }); // 列表點擊 (事件委託) listContainer.addEventListener('click', function(e) { var item = e.target.closest('.panel-item'); if (item) { selectedIndex = parseInt(item.dataset.index); confirmSelection(); } }); // 懸停高亮 listContainer.addEventListener('mouseover', function(e) { var item = e.target.closest('.panel-item'); if (item) setActive(item); }); // 按鈕 panel.querySelector('.btn-clear').onclick = function() { currentInput.value = ''; close(); }; panel.querySelector('.btn-close').onclick = close; mask.onclick = close; } function open(input, data, options) { currentInput = input; currentData = data || []; options = options || {}; selectedIndex = -1; createPanel(); positionPanel(input); renderList(''); searchInput.value = ''; searchInput.focus(); mask.style.display = 'block'; panel.style.display = 'block'; } function positionPanel(input) { var rect = input.getBoundingClientRect(); panel.style.left = rect.left + 'px'; panel.style.top = (rect.bottom + 5) + 'px'; panel.style.width = rect.width + 'px'; // 視口邊界檢查 var panelRect = panel.getBoundingClientRect(); if (panelRect.right > window.innerWidth) { panel.style.left = (window.innerWidth - panelRect.width - 10) + 'px'; } if (panelRect.bottom > window.innerHeight) { panel.style.top = (rect.top - panelRect.height - 5) + 'px'; } } function renderList(filter) { var html = ''; var filtered = filter ? currentData.filter(function(item) { return item.name.toLowerCase().indexOf(filter) > -1; }) : currentData; filtered.forEach(function(item, index) { html += '
' + (item.id ? item.id + ': ' : '') + item.name + '
'; }); listContainer.innerHTML = html || '
無匹配數據
'; selectedIndex = -1; } function setActive(item) { var items = listContainer.querySelectorAll('.panel-item'); items.forEach(function(el) { el.style.background = ''; }); item.style.background = '#e6f7ff'; selectedIndex = parseInt(item.dataset.index); } function navigate(dir) { var items = listContainer.querySelectorAll('.panel-item'); if (!items.length) return; selectedIndex = (selectedIndex + dir + items.length) % items.length; setActive(items[selectedIndex]); items[selectedIndex].scrollIntoView({block: 'nearest'}); } function confirmSelection() { if (selectedIndex < 0) return; var filtered = searchInput.value.trim() ? currentData.filter(function(item) { return item.name.toLowerCase().indexOf(searchInput.value.trim().toLowerCase()) > -1; }) : currentData; var selected = filtered[selectedIndex]; if (selected) { var mode = currentInput.dataset.appendMode === 'true' ? 'append' : 'replace'; if (mode === 'append') { currentInput.value += (currentInput.value ? '; ' : '') + selected.name; } else { currentInput.value = selected.name; } currentInput.dispatchEvent(new Event('change', {bubbles: true})); } close(); } function close() { mask.style.display = 'none'; panel.style.display = 'none'; currentInput = null; } // 公開 API return { attach: function(input, data, options) { input.addEventListener('click', function() { open(input, data, options); }); input.addEventListener('focus', function() { open(input, data, options); }); } }; })(); // 初始化綁定 document.addEventListener('DOMContentLoaded', function() { var inputs = document.querySelectorAll('[data-select-panel]'); inputs.forEach(function(input) { var dataName = input.dataset.selectPanel; // 數組變量名 var data = window[dataName] || []; var options = { appendMode: input.dataset.appendMode === 'true' }; SelectPanel.attach(input, data, options); }); });

HTML 使用示例

<!-- 數據源 (全局變量) -->
<script>
var userList = [
    {id: 1, name: '張三'}, {id: 2, name: '李四'}, {id: 3, name: '王五'},
    {id: 4, name: '趙六'}, {id: 5, name: '錢七'}, {id: 6, name: '孫八'}
];
</script>

<!-- 替換模式 -->
<input type="text" data-select-panel="userList" placeholder="點擊選擇用戶" />

<!-- 追加模式 (多選) -->
<input type="text" data-select-panel="userList" data-append-mode="true" placeholder="點擊添加用戶" />

CSS 樣式建議

.select-panel-mask {transition: opacity 0.2s;}
.select-panel {transition: all 0.2s; border-radius: 4px;}
.select-panel .panel-item:hover {background: #e6f7ff;}
.select-panel .panel-item.active {background: #bae7ff;}
.select-panel .panel-search:focus {outline: none; border-color: #1890ff; box-shadow: 0 0 0 2px rgba(24,144,255,0.2);}

擴展建議

  • 📄 分頁加載:大數據量時渲染前 50 條,滾動到底部加載更多
  • 🏷️ 分組顯示:支持 {group: '部門A', items: [...]} 結構
  • ✅ 多選模式:Checkbox 列表 + 底部確認按鈕
  • 🔌 異步數據:data-select-panel-url="/api/users" 自動請求
  • ♿ 無障礙:ARIA 屬性 role="listbox"、aria-activedescendant

此組件零依賴、體積小 (~2KB gzip)、易擴展,適合輕量級項目直接嵌入。

copyright © 萬盛學電腦網 all rights reserved