当前位置:首页 > JavaScript

实现autocomplete功能js

2026-04-07 14:24:05JavaScript

使用HTML5的datalist元素

HTML5提供了原生支持autocomplete的<datalist>元素,简单易用且不需要额外JavaScript代码。创建一个输入框并关联预定义的选项列表。

<input list="browsers" placeholder="选择浏览器">
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Safari">
  <option value="Edge">
  <option value="Opera">
</datalist>

纯JavaScript实现

对于更复杂的场景,可以用纯JavaScript监听输入事件并动态生成建议列表。创建一个隐藏的<div>作为下拉容器,根据输入内容过滤并显示匹配项。

const suggestions = ['Apple', 'Banana', 'Cherry', 'Date'];
const input = document.getElementById('fruitInput');
const dropdown = document.getElementById('suggestions');

input.addEventListener('input', function() {
  const inputVal = this.value.toLowerCase();
  dropdown.innerHTML = '';

  if (!inputVal) return;

  const matches = suggestions.filter(item => 
    item.toLowerCase().includes(inputVal)
  );

  matches.forEach(match => {
    const div = document.createElement('div');
    div.textContent = match;
    div.addEventListener('click', () => {
      input.value = match;
      dropdown.innerHTML = '';
    });
    dropdown.appendChild(div);
  });
});

使用jQuery实现

如果项目中已使用jQuery,可以简化DOM操作。通过jQuery的事件绑定和元素操作快速实现autocomplete功能。

$('#fruitInput').on('input', function() {
  const inputVal = $(this).val().toLowerCase();
  $('#suggestions').empty();

  if (!inputVal) return;

  const matches = suggestions.filter(item => 
    item.toLowerCase().includes(inputVal)
  );

  matches.forEach(match => {
    $('<div>').text(match)
      .click(() => {
        $('#fruitInput').val(match);
        $('#suggestions').empty();
      })
      .appendTo('#suggestions');
  });
});

使用第三方库

对于生产环境,推荐使用成熟的autocomplete库如:

  • jQuery UI Autocomplete
  • Awesomplete
  • Algolia Autocomplete

以jQuery UI为例:

$('#tags').autocomplete({
  source: ['ActionScript', 'AppleScript', 'Asp']
});

远程数据源实现

当需要从服务器获取建议时,可以使用AJAX请求。以下示例展示如何从API获取动态建议。

input.addEventListener('input', debounce(function() {
  fetch(`/api/search?q=${this.value}`)
    .then(response => response.json())
    .then(data => {
      dropdown.innerHTML = '';
      data.items.forEach(item => {
        const div = document.createElement('div');
        div.textContent = item.name;
        div.addEventListener('click', () => {
          input.value = item.name;
          dropdown.innerHTML = '';
        });
        dropdown.appendChild(div);
      });
    });
}, 300));

function debounce(fn, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, arguments), delay);
  };
}

样式优化

为下拉建议列表添加基础CSS样式,提升用户体验。

#suggestions {
  position: absolute;
  border: 1px solid #ddd;
  max-height: 200px;
  overflow-y: auto;
}

#suggestions div {
  padding: 8px;
  cursor: pointer;
}

#suggestions div:hover {
  background-color: #f0f0f0;
}

键盘导航支持

增强可访问性,允许用户通过键盘选择建议项。

实现autocomplete功能js

input.addEventListener('keydown', function(e) {
  const items = dropdown.querySelectorAll('div');
  let current = Array.from(items).findIndex(item => 
    item.classList.contains('active')
  );

  if (e.key === 'ArrowDown') {
    e.preventDefault();
    current = (current + 1) % items.length;
  } else if (e.key === 'ArrowUp') {
    e.preventDefault();
    current = (current - 1 + items.length) % items.length;
  } else if (e.key === 'Enter' && current >= 0) {
    e.preventDefault();
    input.value = items[current].textContent;
    dropdown.innerHTML = '';
    return;
  }

  items.forEach((item, i) => 
    item.classList.toggle('active', i === current)
  );
});

分享给朋友:

相关文章

vue实现倍速播放功能

vue实现倍速播放功能

实现倍速播放功能的方法 在Vue中实现倍速播放功能通常涉及HTML5的<video>元素或第三方播放器库(如video.js)的API调用。以下是具体实现方式: 使用原生HTML5 vi…

vue前端实现打印功能

vue前端实现打印功能

使用Vue实现前端打印功能 使用window.print()方法 Vue中可以直接调用浏览器的window.print()方法实现打印功能。这种方法简单快捷,适用于打印整个页面或特定区域。 meth…

php实现分页功能

php实现分页功能

PHP实现分页功能的方法 数据库查询与分页逻辑 使用SQL的LIMIT和OFFSET实现分页。假设每页显示10条数据,当前页码为$page: $perPage = 10; $page = isset…

vue实现tab功能

vue实现tab功能

Vue实现Tab功能的方法 使用动态组件和v-for指令 在Vue中实现Tab功能可以通过动态组件和v-for指令结合完成。定义一个包含tab标题和对应内容的数组,使用v-for渲染tab标题,并通过…

vue实现功能列表

vue实现功能列表

Vue 实现功能列表的方法 在 Vue 中实现功能列表通常涉及数据绑定、列表渲染、事件处理和状态管理。以下是几种常见的方法: 数据驱动列表渲染 使用 v-for 指令可以轻松实现列表渲染。假设有一个…

vue实现截图功能

vue实现截图功能

Vue实现截图功能的方法 使用html2canvas库 html2canvas是一个流行的JavaScript库,可以将HTML元素转换为Canvas,进而生成图片。在Vue项目中安装html2can…