鼠标点击时,下拉菜单出现
鼠标划过或按键盘上下箭头时,选中的菜单背景色变化,选项内容显示在输入框内
鼠标点击或按下回车或空格键时,对应的内容显示在输入框内且下拉菜单消失
效果图
HTML
<div id="cont">
<input type="text" name="" id="txt" value="" />
<ul>
<li>选项1</li>
<li>选项2</li>
<li>选项3</li>
<li>选项4</li>
<li>选项5</li>
<li>选项6</li>
</ul>
</div>
CSS
<style type="text/css">
* {
margin: 0;
padding: 0;
list-style: none;
}
#cont {
width: 300px;
margin: 40px auto;
}
input {
width: 296px;
height: 40px;
}
ul {
background: #eee;
display: none;
}
ul li {
line-height: 30px;
text-indent: 20px;
border-bottom: solid 1px black;
}
ul li.active {
background: #ccc;
}
</style>
JS
var input = document.querySelector('input');
var ul = document.querySelector('ul');
var li = document.querySelectorAll('li');
var index = -1;
//输入框获取焦点时,所有的下拉菜单出现
input.onfocus = function () {
ul.style.display = 'block';
}
//输入框失去焦点时,所有的下拉菜单出现
input.onblur = function () {
ul.style.display = 'none';
}
//鼠标滑过时,对应的li背景色改变,li内容显示在输入框中
li.forEach(function (li, key) {
//鼠标移入
li.onmouseover = function overFn() {
var res1 = document.querySelector('.active');
res1 && (res1.className = "");
input.value = this.innerText;
this.className = 'active';
index = key;
};
li.onmouseout = outFn;//鼠标移出
})
//鼠标移出
function outFn() {
this.className = '';
}
//键盘上下键选择 上38,下40
//按上键时,索引--,对应的li背景色改变,li内容显示在输入框中
//按下键时,索引++,对应的li背景色改变,li内容显示在输入框中
input.onkeydown = function (eve) {
eve = eve || window.event;
select(eve);
}
function select(eve) {
var tops = eve.keyCode;
var res = document.querySelector('.active');
res && (res.className = "");
for (var i = 0; i < li.length; i++) {
li[i].className = '';
}
if (eve.keyCode == 38) {
index--;
if (index < 0) {
index = li.length - 1
}
}
if (eve.keyCode == 40) {
index++;
if (index > li.length - 1) {
index = 0;
}
}
if (eve.keyCode == 32 || eve.keyCode == 13) {
if (index == -1) {
input.value = '';
} else {
input.value = li[index].innerText;
}
ul.style.display = 'none'
}
if (eve.keyCode == 8) {
index = -1;
}
if (index != -1) {
li[index].className = 'active';
input.value = li[index].innerText;
} else {
input.value = '';
}
console.log(eve.keyCode);
}