当前位置:首页 > JavaScript

js 实现combox

2026-02-02 09:25:29JavaScript

实现基本的 ComboBox 功能

使用 HTML、CSS 和 JavaScript 创建一个简单的 ComboBox,包含输入框和下拉选项列表:

<div class="combo-box">
  <input type="text" class="combo-input" placeholder="Select an option">
  <ul class="combo-options">
    <li>Option 1</li>
    <li>Option 2</li>
    <li>Option 3</li>
  </ul>
</div>

<style>
.combo-box {
  position: relative;
  width: 200px;
}
.combo-input {
  width: 100%;
  padding: 8px;
}
.combo-options {
  position: absolute;
  width: 100%;
  margin: 0;
  padding: 0;
  list-style: none;
  border: 1px solid #ddd;
  max-height: 200px;
  overflow-y: auto;
  display: none;
}
.combo-options li {
  padding: 8px;
  cursor: pointer;
}
.combo-options li:hover {
  background-color: #f5f5f5;
}
</style>

<script>
const input = document.querySelector('.combo-input');
const options = document.querySelector('.combo-options');

input.addEventListener('focus', () => {
  options.style.display = 'block';
});

input.addEventListener('blur', () => {
  setTimeout(() => {
    options.style.display = 'none';
  }, 200);
});

options.querySelectorAll('li').forEach(option => {
  option.addEventListener('click', () => {
    input.value = option.textContent;
    options.style.display = 'none';
  });
});
</script>

添加键盘导航支持

增强 ComboBox 的交互性,支持键盘上下箭头选择和回车确认:

input.addEventListener('keydown', (e) => {
  const items = options.querySelectorAll('li');
  let currentIndex = Array.from(items).findIndex(item => 
    item.classList.contains('selected')
  );

  if (e.key === 'ArrowDown') {
    e.preventDefault();
    currentIndex = (currentIndex + 1) % items.length;
    updateSelection(items, currentIndex);
  } else if (e.key === 'ArrowUp') {
    e.preventDefault();
    currentIndex = (currentIndex - 1 + items.length) % items.length;
    updateSelection(items, currentIndex);
  } else if (e.key === 'Enter') {
    e.preventDefault();
    if (currentIndex >= 0) {
      input.value = items[currentIndex].textContent;
      options.style.display = 'none';
    }
  }
});

function updateSelection(items, index) {
  items.forEach(item => item.classList.remove('selected'));
  items[index].classList.add('selected');
  items[index].scrollIntoView({ block: 'nearest' });
}

实现过滤功能

为 ComboBox 添加输入时实时过滤选项的功能:

input.addEventListener('input', () => {
  const searchTerm = input.value.toLowerCase();
  const items = options.querySelectorAll('li');

  items.forEach(item => {
    const text = item.textContent.toLowerCase();
    item.style.display = text.includes(searchTerm) ? 'block' : 'none';
  });

  options.style.display = 'block';
});

使用数据动态生成选项

从数据数组动态生成 ComboBox 选项:

const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

function populateOptions() {
  options.innerHTML = '';
  data.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    options.appendChild(li);
  });

  options.querySelectorAll('li').forEach(option => {
    option.addEventListener('click', () => {
      input.value = option.textContent;
      options.style.display = 'none';
    });
  });
}

populateOptions();

添加自定义事件

为 ComboBox 添加自定义事件处理:

function triggerEvent(name, detail) {
  const event = new CustomEvent(name, { detail });
  input.dispatchEvent(event);
}

input.addEventListener('change', () => {
  triggerEvent('combochange', { value: input.value });
});

// 使用示例
input.addEventListener('combochange', (e) => {
  console.log('Selected value changed to:', e.detail.value);
});

完整组件封装

将 ComboBox 封装为可重用的类:

js 实现combox

class ComboBox {
  constructor(container, options) {
    this.container = container;
    this.options = options.data || [];
    this.init();
  }

  init() {
    this.container.innerHTML = `
      <input type="text" class="combo-input" placeholder="${this.options.placeholder || 'Select'}">
      <ul class="combo-options"></ul>
    `;

    this.input = this.container.querySelector('.combo-input');
    this.optionsList = this.container.querySelector('.combo-options');
    this.renderOptions();
    this.setupEvents();
  }

  renderOptions() {
    this.optionsList.innerHTML = this.options
      .map(item => `<li>${item}</li>`)
      .join('');
  }

  setupEvents() {
    // 添加之前的事件处理代码
  }
}

// 使用示例
const combo = new ComboBox(document.getElementById('combo-container'), {
  data: ['Red', 'Green', 'Blue'],
  placeholder: 'Select a color'
});

标签: jscombox
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含inpu…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1; le…

js验证码的实现

js验证码的实现

验证码的基本实现原理 验证码(CAPTCHA)的核心目标是区分人类用户和自动化程序。JavaScript可用于生成或验证客户端验证码,但需注意纯前端验证可能被绕过,通常需结合后端验证。 纯前端验证码…