自动完成组件通过监听输入事件过滤数据并显示匹配建议。首先创建输入框和隐藏的下拉列表,使用css定位与样式控制外观;javaScript定义数据源,实时匹配用户输入并动态渲染建议项,支持点击选中和外部点击关闭。可扩展异步加载、键盘导航、高亮匹配及防抖优化。

自动完成组件(Autocomplete)是一种常见的ui功能,用户在输入时会看到匹配的建议列表。下面是一个使用原生javascript实现的简单自动完成组件,不依赖任何框架或库。
基本结构与html
先定义一个输入框和一个用于显示建议的下拉列表容器:
<div class="autocomplete"> <input type="text" id="searchInput" placeholder="输入内容..."> <ul id="suggestions" class="suggestions-list"></ul> </div>
样式设计(CSS)
为了让组件看起来更清晰,添加一些基础样式:
.autocomplete { position: relative; width: 300px; } #searchInput { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; } .suggestions-list { position: absolute; top: 100%; left: 0; right: 0; margin: 0; padding: 0; list-style: none; border: 1px solid #ddd; border-top: none; max-height: 200px; overflow-y: auto; background: white; z-index: 10; display: none; } .suggestions-list.visible { display: block; } .suggestions-list li { padding: 10px; cursor: pointer; } .suggestions-list li:hover { background-color: #f0f0f0; }
JavaScript逻辑实现
接下来是核心部分:监听输入事件,过滤数据并显示建议。
立即学习“Java免费学习笔记(深入)”;
// 建议数据源 const data = [ "JavaScript", "Java", "python", "php", "Perl", "c++", "C#", "go", "Ruby", "Swift", "Kotlin" ]; const input = document.getElementById("searchInput"); const suggestionsList = document.getElementById("suggestions"); // 渲染建议项 function renderSuggestions(matches) { suggestionsList.innerHTML = ''; if (matches.length === 0) { suggestionsList.classlist.remove('visible'); return; } matches.forEach(item => { const li = document.createElement("li"); li.textContent = item; li.addEventListener("click", () => { input.value = item; suggestionsList.classList.remove('visible'); }); suggestionsList.appendChild(li); }); suggestionsList.classList.add('visible'); } // 获取匹配项 function getMatches(inputValue) { return data.filter(item => item.toLowerCase().includes(inputValue.toLowerCase()) ); } // 输入事件处理 input.addEventListener("input", function () { const value = this.value.trim(); if (value === "") { suggestionsList.classList.remove('visible'); return; } const matches = getMatches(value); renderSuggestions(matches); }); // 点击外部关闭建议列表 document.addEventListener("click", function (e) { if (e.target !== input && e.target !== suggestionsList) { suggestionsList.classList.remove('visible'); } });
功能扩展建议
这个基础版本可以进一步增强:
- 异步支持:将data替换为fetch请求,从后端获取建议数据
- 键盘导航:支持上下键选择,回车确认
- 高亮匹配文字:在建议中加粗显示用户输入的部分
- 防抖机制:避免频繁触发搜索,提升性能
基本上就这些,不复杂但容易忽略细节。