JS实现autocomplete
实现基础Autocomplete功能
使用HTML和JavaScript创建一个简单的autocomplete功能。HTML部分需要一个输入框和一个用于显示建议的容器。
<input type="text" id="autocomplete-input" placeholder="Type something...">
<div id="suggestions-container"></div>
const input = document.getElementById('autocomplete-input');
const suggestionsContainer = document.getElementById('suggestions-container');
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
input.addEventListener('input', function() {
const inputValue = this.value.toLowerCase();
const filteredData = data.filter(item =>
item.toLowerCase().includes(inputValue)
);
renderSuggestions(filteredData);
});
function renderSuggestions(items) {
suggestionsContainer.innerHTML = '';
if (items.length === 0) return;
const ul = document.createElement('ul');
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
li.addEventListener('click', function() {
input.value = item;
suggestionsContainer.innerHTML = '';
});
ul.appendChild(li);
});
suggestionsContainer.appendChild(ul);
}
使用Debounce优化性能
对于大量数据或远程请求,使用debounce技术减少频繁触发事件。
function debounce(func, delay) {
let timeoutId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, args), delay);
};
}
input.addEventListener('input', debounce(function() {
const inputValue = this.value.toLowerCase();
// 处理过滤逻辑...
}, 300));
远程数据获取
从API获取autocomplete建议数据,使用fetch或axios。
input.addEventListener('input', debounce(function() {
const inputValue = this.value.trim();
if (inputValue.length < 2) return;
fetch(`https://api.example.com/search?q=${inputValue}`)
.then(response => response.json())
.then(data => renderSuggestions(data.results))
.catch(error => console.error('Error:', error));
}, 300));
添加键盘导航
允许用户使用键盘上下箭头选择建议项。
input.addEventListener('keydown', function(e) {
const items = suggestionsContainer.querySelectorAll('li');
if (!items.length) return;
let activeIndex = Array.from(items).findIndex(item =>
item.classList.contains('active')
);
if (e.key === 'ArrowDown') {
e.preventDefault();
activeIndex = (activeIndex + 1) % items.length;
} else if (e.key === 'ArrowUp') {
e.preventDefault();
activeIndex = (activeIndex - 1 + items.length) % items.length;
} else if (e.key === 'Enter' && activeIndex >= 0) {
input.value = items[activeIndex].textContent;
suggestionsContainer.innerHTML = '';
return;
}
items.forEach(item => item.classList.remove('active'));
items[activeIndex].classList.add('active');
});
添加样式增强用户体验
为autocomplete添加基本CSS样式。
#suggestions-container {
position: relative;
width: 100%;
}
#suggestions-container ul {
position: absolute;
width: 100%;
list-style: none;
padding: 0;
margin: 0;
border: 1px solid #ddd;
max-height: 200px;
overflow-y: auto;
}
#suggestions-container li {
padding: 8px 12px;
cursor: pointer;
background: white;
}
#suggestions-container li:hover,
#suggestions-container li.active {
background: #f0f0f0;
}
高级功能扩展
对于更复杂的需求,可以考虑以下扩展:

- 分组显示建议项
- 显示每个项的附加信息(如图标、描述)
- 多选autocomplete
- 自定义匹配高亮
- 本地存储最近选择项
// 示例:高亮匹配文本
function highlightMatch(text, match) {
const regex = new RegExp(`(${match})`, 'gi');
return text.replace(regex, '<strong>$1</strong>');
}
// 在renderSuggestions中使用
li.innerHTML = highlightMatch(item, input.value);






