js实现lookupedit
实现 LookupEdit 功能
LookupEdit 是一种常见的用户界面控件,允许用户在输入时从下拉列表中选择值。以下是使用 JavaScript 和 HTML 实现 LookupEdit 的方法。
HTML 结构
创建一个基本的 HTML 结构,包含输入框和下拉列表。
<div class="lookup-edit-container">
<input type="text" id="lookupInput" placeholder="Type to search...">
<div id="dropdownList" class="dropdown-list"></div>
</div>
CSS 样式
为输入框和下拉列表添加样式,确保下拉列表在输入框下方显示。
.lookup-edit-container {
position: relative;
width: 300px;
}
#lookupInput {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.dropdown-list {
position: absolute;
width: 100%;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ccc;
background: white;
display: none;
}
.dropdown-list div {
padding: 8px;
cursor: pointer;
}
.dropdown-list div:hover {
background-color: #f0f0f0;
}
JavaScript 实现
使用 JavaScript 实现 LookupEdit 的核心功能,包括输入监听、下拉列表显示和选择功能。
document.addEventListener('DOMContentLoaded', function() {
const input = document.getElementById('lookupInput');
const dropdown = document.getElementById('dropdownList');
// 模拟数据源
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape'];
// 输入事件监听
input.addEventListener('input', function() {
const inputText = input.value.toLowerCase();
const filteredData = data.filter(item =>
item.toLowerCase().includes(inputText)
);
updateDropdown(filteredData);
});
// 更新下拉列表
function updateDropdown(items) {
dropdown.innerHTML = '';
if (items.length === 0) {
dropdown.style.display = 'none';
return;
}
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
div.addEventListener('click', function() {
input.value = item;
dropdown.style.display = 'none';
});
dropdown.appendChild(div);
});
dropdown.style.display = 'block';
}
// 点击外部关闭下拉列表
document.addEventListener('click', function(event) {
if (!input.contains(event.target) && !dropdown.contains(event.target)) {
dropdown.style.display = 'none';
}
});
});
功能扩展
如果需要从服务器动态加载数据,可以使用 fetch API 或类似方法。
input.addEventListener('input', async function() {
const inputText = input.value;
const response = await fetch(`/api/search?q=${encodeURIComponent(inputText)}`);
const data = await response.json();
updateDropdown(data);
});
键盘导航
为提升用户体验,可以添加键盘导航功能。

input.addEventListener('keydown', function(event) {
const items = dropdown.querySelectorAll('div');
if (!items.length) return;
let currentIndex = -1;
items.forEach((item, index) => {
if (item.classList.contains('active')) {
currentIndex = index;
item.classList.remove('active');
}
});
if (event.key === 'ArrowDown') {
event.preventDefault();
currentIndex = (currentIndex + 1) % items.length;
} else if (event.key === 'ArrowUp') {
event.preventDefault();
currentIndex = (currentIndex - 1 + items.length) % items.length;
} else if (event.key === 'Enter' && currentIndex >= 0) {
event.preventDefault();
input.value = items[currentIndex].textContent;
dropdown.style.display = 'none';
return;
}
if (currentIndex >= 0) {
items[currentIndex].classList.add('active');
}
});
以上代码实现了一个基本的 LookupEdit 控件,可以根据实际需求进一步扩展功能。






