<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
.current{background-color:red}
</style>
</head>
<body>
<input id="SearchResult" type="text"/>
<ul id="ulSearch">
<li>中海创集团</li>
<li>福大自动化</li>
<li>奥迈软件e79fa5e98193e4b893e5b19e31333366306435</li>
<li>自控规划部</li>
<li>爱普科技</li>
<li>IAP</li>
<li>ISEE</li>
<li>联排联调</li>
<li>水系</li>
<li>云计算</li>
</ul>
<script>
var list = document.getElementById("ulSearch").getElementsByTagName("li");
var index = -1;
function addIndex() {
index = index>=9 ? 0 : ++index;
return index;
}
function reduceIndex() {
index = index <= 0 ? 9 : --index;
return index;
}
document.onkeydown = function(e) {
e = e || window.event;
switch(e.keyCode){
case 13:
var t = document.getElementById("ulSearch").getElementsByTagName("li")[index].innerHTML;
document.getElementById("SearchResult").value = t;
break;
case 38:
reduceIndex();
setLiColorByClass();
break;
case 40:
addIndex();
setLiColorByClass();
break;
}
function setLiColorByClass(){
for(var i = 0,len=list.length; i<len; i++) {
list[i].className = i==index ? "current" : "";
}
}
};
</script>
</body>
</html>
转载:https://zhidao.baidu.com/question/584524937.html
优化版(向下到最后一个li后再按下箭头则循环到第一个li):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
.current{background-color:red}
</style>
</head>
<body>
<input id="SearchResult" type="text"/>
<ul id="ulSearch">
<li>中海创集团</li>
<li>福大自动化</li>
<li>奥迈软件e79fa5e98193e4b893e5b19e31333366306435</li>
<li>自控规划部</li>
<li>爱普科技</li>
<li>IAP</li>
<li>ISEE</li>
<li>联排联调</li>
<li>水系</li>
<li>云计算</li>
</ul>
<script>
var list = document.getElementById("ulSearch").getElementsByTagName("li");
var index = -1;
var liLength = list.length-1;//比上一版多了-1
function addIndex() {
index = index>= liLength ? 0 : ++index;
return index;
}
function reduceIndex() {
index = index <= 0 ? liLength : --index;
return index;
}
document.onkeydown = function(e) {
e = e || window.event;
switch(e.keyCode){
case 13:
var t = document.getElementById("ulSearch").getElementsByTagName("li")[index].innerHTML;
document.getElementById("SearchResult").value = t;
break;
case 38:
reduceIndex();
setLiColorByClass();
break;
case 40:
addIndex();
setLiColorByClass();
break;
}
};
function setLiColorByClass(){
for(var i = 0,len=list.length; i<len; i++) {
list[i].className = i==index ? "current" : "";
}
console.log(list.length);
}
</script>
</body>
</html>