当前位置:首页 > 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技术减少频繁触发事件。

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

高级功能扩展

对于更复杂的需求,可以考虑以下扩展:

JS实现autocomplete

  • 分组显示建议项
  • 显示每个项的附加信息(如图标、描述)
  • 多选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
分享给朋友:

相关文章

实现阶乘JS

实现阶乘JS

递归实现阶乘 递归是一种直接按照数学定义实现阶乘的方法。n的阶乘可以表示为n乘以(n-1)的阶乘,基础情况是0的阶乘为1。 function factorialRecursive(n) { if…

JS实现并发请求

JS实现并发请求

使用Promise.all实现并发请求 Promise.all可以同时发起多个异步请求,并在所有请求完成后统一处理结果。该方法适用于需要同时获取多个独立数据的场景。 const urls = ['u…

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Autocomplete(自动完成)是一种常见的用户输入辅助功能,能够根据用户输入提供建议列表。以下是几种在 Vue 中实现 Autocomplete 的…

JS实现跳表

JS实现跳表

跳表(Skip List)简介 跳表是一种基于概率的平衡数据结构,通过多层链表实现高效查找、插入和删除操作,时间复杂度为 $O(\log n)$。其核心思想是通过“跳跃”式访问节点减少遍历次数。 跳…

JS实现上传

JS实现上传

上传文件的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。以下是一个基础示例: <input ty…

JS如何实现左右滑动

JS如何实现左右滑动

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来跟踪触摸位置。记录起始点坐标和移动过程中的坐标变化。 let startX = 0; let endX…