物料UI(Material User Interface)是指遵循Material Design设计规范的界面设计。自动完成功能通常用于输入框,允许用户从预定义的选项列表中选择一个或多个项目。当用户选择一个项目时,该项目通常会被标记为已选择,并从选项列表中移除,以避免重复选择。
以下是一个简单的多选自动完成的示例代码,使用HTML、CSS和JavaScript实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multi-Select AutoComplete</title>
<style>
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
background-color: #e9e9e9;
}
</style>
</head>
<body>
<input type="text" id="myInput" onkeyup="filterFunction()" placeholder="Select items...">
<div id="autocomplete-list" class="autocomplete-items"></div>
<script>
const options = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"];
let selectedItems = [];
function filterFunction() {
const input = document.getElementById("myInput");
const filter = input.value.toUpperCase();
const autocompleteList = document.getElementById("autocomplete-list");
autocompleteList.innerHTML = "";
for (let i = 0; i < options.length; i++) {
if (options[i].toUpperCase().indexOf(filter) > -1 && !selectedItems.includes(options[i])) {
const div = document.createElement("div");
div.innerHTML = options[i];
div.onclick = function() {
input.value = "";
selectedItems.push(options[i]);
filterFunction();
updateSelectedItems();
};
autocompleteList.appendChild(div);
}
}
}
function updateSelectedItems() {
console.log("Selected Items:", selectedItems);
}
</script>
</body>
</html>
问题:已选择的项目仍然显示在选项列表中。
原因:可能是由于在选择项目后没有正确地从选项列表中移除该项目。
解决方法:
在上述示例代码中,selectedItems
数组用于跟踪已选择的项目,并在选择新项目时更新该数组。这样可以确保已选择的项目不会再次出现在选项列表中。
通过这种方式,可以有效地实现多选自动完成功能,并提高用户体验。
领取专属 10元无门槛券
手把手带您无忧上云