当前位置:首页 > JavaScript

JS实现autocomplete

2026-04-06 10:14:26JavaScript

实现基础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技术减少频繁触发事件。

JS实现autocomplete

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

添加键盘导航

允许用户使用键盘上下箭头选择建议项。

JS实现autocomplete

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

标签: JSautocomplete
分享给朋友:

相关文章

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Autocomplete(自动补全)功能在 Vue 中可以通过多种方式实现,以下是几种常见的方法: 使用原生 HTML 和 Vue 数据绑定 通过 Vu…

JS实现跳表

JS实现跳表

跳表的基本概念 跳表(Skip List)是一种基于概率的数据结构,允许快速查询、插入和删除操作,时间复杂度平均为O(log n)。它通过多层链表实现,每一层都是下一层的子集,高层链表跳过多个元素,从…

JS实现日期滚动选择

JS实现日期滚动选择

实现日期滚动选择的基本思路 使用HTML、CSS和JavaScript创建一个日期滚动选择器,允许用户通过滚动选择年、月、日。核心是通过监听滚动事件,动态更新显示的值。 HTML结构 创建一个包含年…

JS实现一个并发函数

JS实现一个并发函数

实现并发控制的几种方法 在JavaScript中实现并发控制可以通过多种方式,以下是几种常见的方法: Promise.all 使用Promise.all可以并行执行多个异步任务,等待所有任务完成后再…

JS实现ln

JS实现ln

在JavaScript中实现自然对数(ln)功能可以通过以下几种方式完成: 使用Math对象的原生方法 JavaScript内置的Math对象提供了Math.log()方法,该方法默认计算以…

动态实现JS

动态实现JS

动态实现 JavaScript 的方法 动态加载脚本 通过创建 script 元素并插入到 DOM 中实现动态加载。例如: const script = document.createEleme…