JS问题 ,求各位大神帮帮忙啊
问题:我在写个类似于百度搜索栏的功能,在实现当<input>标签失去焦点时,下拉列表隐藏,当点击下拉列表中的某个项时就把该项的内容写入到<input>标签内,并且下拉列表隐藏,出问题了。
因为<input>标签我设的是onblur事件时,下拉列表隐藏,那么当 点击下拉列表中的某项时,先执行的时<input>标签的onblur事件,隐藏了下拉列表,那样就无法执行写入操作了。
具体代码如下:<style type="text/css">
#txtInput
{
width: 150px;
height: 20px;
border: 1px solid #9c9c9c;
padding: 0 2px;
}
#txtInput:hover
{
border: 1px solid blue;
}
#list
{
display: none;
top: 30px;
left: 8px;
position: absolute;
min-width: 154px;
border: 1px solid #9c9c9c;
background-color: white;
}
ul
{
padding:0px;
margin:0px;
list-style:none;
cursor:pointer;
}
ul li:hover
{
background-color:#9c9c9c;
}
</style>
<script type="text/javascript">
function txtFocus() {
var txtInput = document.getElementById("txtInput");
var divList = document.getElementById("list");
if (txtInput.value != "") {
divList.style.display = "block";
}
}
function txtBlur() {
var txtInput = document.getElementById("txtInput");
var divList = document.getElementById("list");
divList.style.display = "block";
}
function txtChange() {
var txtInput = document.getElementById("txtInput");
var divList = document.getElementById("list");
if (txtInput.value != "") {
divList.style.display = "block";
}
else {
divList.style.display = "none";
}
}
function listClick(num) {
var txtInput = document.getElementById("txtInput");
var divList = document.getElementById("list");
var arr = divList.getElementsByTagName("li");
for (var i = 0; i < arr.length; i++) {
if (String(i) == num) {
txtInput.value = arr[i].innerText;
divList.style.display = "none";
}
}
}
</script>
//html部分
<input type="text" id="txtInput" onblur="txtBlur()" onfocus="txtFocus()" onkeyup="txtChange()" />
<div id="list">
<ul>
<li onclick="listClick(0)">阿达的身份</li>
<li onclick="listClick(1)">a奥迪啊dsfad</li>
<li onclick="listClick(2)">ad敖德萨sfa</li>
<li onclick="listClick(3)">爱的发的</li>
<li onclick="listCl