<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
ul li{
list-style: none;
}
input{
width: 298px;
height: 40px;
}
#box{
width: 300px;
height: 600px;
margin: 100px auto;
}
ul{
display: none;
}
ul li{
width: 300px;
height: 50px;
background: #eee;
border: 1px solid #000;
font-size: 24px;
line-height: 50px;
}
.active{
background: #ff0;
}
</style>
</head>
<body>
<div id="box">
<input type="text">
<ul>
<li>水电费绝对是1</li>
<li>水电费绝对是2</li>
<li>水电费绝对是3</li>
<li>水电费绝对是4</li>
<li>水电费绝对是5</li>
</ul>
</div>
</body>
<script>
var box = document.getElementById('box'),
inp = document.querySelector('input'),
uls = document.querySelector('ul'),
list = document.querySelectorAll('li');
var index = -1;
inp.onfocus = function(){
uls.style.display = 'block';
for( var i = 0;i < list.length;i++){
list[i].index = i;
list[i].onmouseover = function(){
index = this.index;
for( var j = 0;j < list.length;j++){
list[j].className = ''
}
list[this.index].className = 'active';
inp.value = list[this.index].innerHTML;
}
}
}
inp.onblur = function(){
uls.style.display = 'none';
}
//键盘事件
inp.onkeydown = function( eve ){
var e = eve || window.event;
var key = e.keyCode || e.which;
if( key == 40){
if(index == list.length-1){
index = 0;
}else{
index++;
}
menu();
}else if( key == 38){
if( index == 0 || index == -1){
index = list.length-1;
}else{
index--;
}
menu();
}
}
function menu(){
for( var i = 0;i < list.length;i++){
for( var j = 0;j < list.length;j++){
list[j].className = '';
}
list[this.index].className = 'active';
inp.value = list[this.index].innerHTML;
}
}
</script>
</html>
网友评论