js实现listbox
实现 ListBox 的基本结构
使用 HTML 和 CSS 创建 ListBox 的基础结构。ListBox 通常由一个可滚动的列表和可选择的项组成。
<div id="listBox" class="list-box">
<div class="list-item">Item 1</div>
<div class="list-item">Item 2</div>
<div class="list-item">Item 3</div>
<div class="list-item">Item 4</div>
</div>
.list-box {
width: 200px;
height: 150px;
border: 1px solid #ccc;
overflow-y: auto;
}
.list-item {
padding: 8px;
cursor: pointer;
}
.list-item:hover {
background-color: #f0f0f0;
}
.list-item.selected {
background-color: #007bff;
color: white;
}
添加 JavaScript 交互逻辑
通过 JavaScript 实现 ListBox 的选择功能,包括单击选中、取消选中等操作。
document.addEventListener('DOMContentLoaded', function() {
const listBox = document.getElementById('listBox');
const items = listBox.querySelectorAll('.list-item');
items.forEach(item => {
item.addEventListener('click', function() {
// 清除所有项的选中状态
items.forEach(i => i.classList.remove('selected'));
// 设置当前项为选中状态
this.classList.add('selected');
});
});
});
支持多选功能
如果需要支持多选(按住 Ctrl 或 Shift 键),可以扩展 JavaScript 逻辑。
document.addEventListener('DOMContentLoaded', function() {
const listBox = document.getElementById('listBox');
const items = listBox.querySelectorAll('.list-item');
items.forEach(item => {
item.addEventListener('click', function(e) {
if (e.ctrlKey) {
// Ctrl 键多选
this.classList.toggle('selected');
} else if (e.shiftKey) {
// Shift 键范围选择(需额外实现逻辑)
} else {
// 单选逻辑
items.forEach(i => i.classList.remove('selected'));
this.classList.add('selected');
}
});
});
});
动态添加和删除项
通过 JavaScript 动态管理 ListBox 中的项,支持添加和删除操作。
function addItem(text) {
const listBox = document.getElementById('listBox');
const newItem = document.createElement('div');
newItem.className = 'list-item';
newItem.textContent = text;
listBox.appendChild(newItem);
}
function removeSelectedItems() {
const listBox = document.getElementById('listBox');
const selectedItems = listBox.querySelectorAll('.list-item.selected');
selectedItems.forEach(item => item.remove());
}
获取选中项的值
提供方法获取当前选中项的文本或索引,便于后续处理。

function getSelectedItems() {
const listBox = document.getElementById('listBox');
const selectedItems = listBox.querySelectorAll('.list-item.selected');
return Array.from(selectedItems).map(item => item.textContent);
}
注意事项
- 确保 CSS 样式兼容不同浏览器,尤其是滚动条和选中状态。
- 动态添加项时需重新绑定事件监听器,或使用事件委托优化性能。
- 多选逻辑可根据需求扩展,例如支持 Shift 键范围选择。
通过以上步骤,可以实现一个功能完整的 ListBox,支持单选、多选、动态增删等常见操作。






