在JavaScript中,要实现一个可编辑的select下拉列表,你可以通过结合HTML的`
下面是一个简单的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editable Dropdown</title>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content li {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
cursor: pointer;
}
.dropdown-content li:hover {background-color: #f1f1f1}
.show {display: block;}
</style>
</head>
<body>
<div class="dropdown">
<input type="text" id="myInput" placeholder="Select or edit item" readonly>
<div id="myDropdown" class="dropdown-content">
<li onclick="selectItem('Apple')">Apple</li>
<li onclick="selectItem('Banana')">Banana</li>
<li onclick="selectItem('Cherry')">Cherry</li>
<li onclick="selectItem('Date')">Date</li>
</div>
</div>
<script>
// Function to show dropdown
function showDropdown() {
document.getElementById("myDropdown").classList.add("show");
}
// Function to hide dropdown
function hideDropdown() {
document.getElementById("myDropdown").classList.remove("show");
}
// Function to select an item
function selectItem(value) {
document.getElementById("myInput").value = value;
hideDropdown();
}
// Event listeners
document.getElementById("myInput").addEventListener("click", function() {
if (this.readOnly) {
this.readOnly = false;
this.focus();
// Optionally hide dropdown here if needed
// hideDropdown();
}
});
document.getElementById("myInput").addEventListener("blur", function() {
this.readOnly = true;
// Optionally, you can add logic here to validate and add the new item to the dropdown
// For simplicity, I'm not doing that in this example
});
// Optional: Add event listener to document to close dropdown on click outside
document.addEventListener("click", function(event) {
if (!event.target.matches('.dropdown') && !event.target.closest('.dropdown-content').matches('.dropdown-content')) {
hideDropdown();
}
});
// Optional: Show dropdown on click
document.getElementById("myInput").addEventListener("focus", showDropdown);
</script>
</body>
</html>
这个示例创建了一个可编辑的“下拉列表”,它实际上是一个输入框(用于编辑或显示选中的项)和一个用`
请注意,这个示例并没有包含将新编辑的文本项添加到下拉列表中的逻辑,因为这通常需要根据具体需求进行实现。你可以根据需要扩展此代码。