我正在try 使用下拉搜索实现一个文本字段.下拉项是具有display: none
CSS属性的div中的按钮.单击时,文本字段应将其内容更改为按钮的内容.
问题是,当焦点从文本字段中移除时,下拉列表应该消失...当我点击一个下拉菜单项时,焦点被移除,按钮消失,其onclick
不会被执行.在执行删除此按钮的代码之前,是否可以执行 Select 名称的按钮代码?
代码:
<!DOCTYPE html>
<html>
<style>
#resident_name_inp:focus {outline: 3px solid #ddd;}
.dd {
position: relative;
display: inline-block;
}
.dd-content {
display: none;
position: absolute;
background-color: #f6f6f6;
overflow: auto;
width: 100%;
border: 1px solid #ddd;
z-index: 1;
}
.dd-content button {
background-color: #ffffff;
width: 100%;
padding-left: 4px;
border: none;
display: block;
}
.dd-content button:hover {
background-color: #ddd;
}
</style>
<body>
<div class="dd">
<input
id="name_inp"
type="text"
placeholder="Search Names..."
onfocus="showNames()"
onfocusout="hideNames()">
<div id="dropdown_names" class="dd-content">
<button type="button" onclick="selectName('alex')">alex</button>
<button type="button" onclick="selectName('jake')">jake</button>
<button type="button" onclick="selecttName('evgen')">evgen</button>
</div>
</div>
</body>
<script>
function showNames() {
document.getElementById("dropdown_names").style.display = 'block'
}
function hideNames() {
document.getElementById("dropdown_names").style.display = 'none'
}
function selectName(name) {
document.getElementById("name_inp").value = name
}
</script>
</html>