可搜索的组合框(Searchable ComboBox)是一种用户界面控件,它结合了文本输入框和列表框的功能。用户可以在文本输入框中输入文本,控件会实时过滤并显示与输入文本匹配的列表项。这种控件通常用于数据验证,确保用户只能从预定义的选项中选择。
以下是一个使用HTML和JavaScript实现可搜索组合框的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Searchable ComboBox</title>
<style>
.combobox-container {
position: relative;
display: inline-block;
}
.combobox-input {
width: 200px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.combobox-options {
position: absolute;
width: 100%;
border: 1px solid #ccc;
border-top: none;
border-radius: 0 0 4px 4px;
display: none;
}
.combobox-options div {
padding: 8px;
cursor: pointer;
}
.combobox-options div:hover {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="combobox-container">
<input type="text" class="combobox-input" placeholder="Select an option">
<div class="combobox-options">
<div>Option 1</div>
<div>Option 2</div>
<div>Option 3</div>
<div>Option 4</div>
</div>
</div>
<script>
const input = document.querySelector('.combobox-input');
const optionsContainer = document.querySelector('.combobox-options');
const options = optionsContainer.querySelectorAll('div');
input.addEventListener('input', () => {
const searchText = input.value.toLowerCase();
options.forEach(option => {
const optionText = option.textContent.toLowerCase();
if (optionText.includes(searchText)) {
option.style.display = 'block';
} else {
option.style.display = 'none';
}
});
});
input.addEventListener('focus', () => {
optionsContainer.style.display = 'block';
});
input.addEventListener('blur', () => {
setTimeout(() => {
optionsContainer.style.display = 'none';
}, 200);
});
options.forEach(option => {
option.addEventListener('click', () => {
input.value = option.textContent;
optionsContainer.style.display = 'none';
});
});
</script>
</body>
</html>
.combobox-options
的display
属性。input
事件监听器正确绑定到输入框。通过以上方法,你可以创建一个功能齐全的可搜索组合框,替换没有帮助器列的数据验证。
领取专属 10元无门槛券
手把手带您无忧上云