HTML页面 Default.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript下拉菜单</title>
<link href="ts.css" rel="stylesheet" type="text/css" />
<script src="ts.js" type="text/javascript"></script>
</head>
<body>
<div id="nav">
<input type="text" id="txt" />
<ul id="clue">
<li>aaa</li>
<li>bbb</li>
<li>ccc</li>
<li>ddd</li>
</ul>
</div>
</body>
</html>
CSS样式表 ts.css
.clear
{
clear : both;
margin-bottom : 100px;
}
* {
padding:0;
margin:0;
}
#nav li
{
list-style-type : none;
padding: 2px 0px 2px 4px;
}
#nav ul
{
width: 152px;
border: 1px solid #AAA;
}
#nav #txt
{
display : block;
}
JavaScript文件 ts.js
window.onload = function(){
var content = new Array("Chen Aaa", "Cai Qbb", "Zhu Ycc", encodeURIComponent("刘伯温"), encodeURIComponent("刘伯伯"),encodeURIComponent("刘德华"), encodeURIComponent("刘邦"), encodeURIComponent("刘亦菲"));
var txt = document.getElementById("txt");
var clue = document.getElementById("clue");
clue.style.display = "none";
txt.onkeyup = function(event){
event = event || window.event;
var input = encodeURIComponent(txt.value);
var result = new Array();
var i, len = input.length, resultLen;
if(input == null || input == ''){
return false;
}
if(event.keyCode == 40 && clue.innerHTML){
var listLen = clue.children.length, i, curIndex = -1;
for(i = 0; i < listLen; i++){
var tmp = clue.childNodes[i].style.backgroundColor;
if(tmp != "" && tmp != null && tmp != "none"){
curIndex = i;
var curList = document.getElementById("list" + i);
if(navigator.appName =="Microsoft Internet Explorer"){
curList.style.backgroundColor = "";
}else{
curList.style.backgroundColor = null;
}
if(i == listLen-1){
curIndex = -1;
}
break;
};
}
var nextList = document.getElementById("list" + (curIndex + 1));
nextList.style.backgroundColor = "#D1E5FC";
txt.value = nextList.innerHTML;
txt.focus();
return false;
}
for(i = 0; i < content.length; i++){
if(input == content[i].substring(0, len)){
result.push(content[i]);
}
}
resultLen = result.length;
resultStr = createList(result);
clue.innerHTML = resultStr;
clue.style.display = "block";
for(i = 0; i < resultLen; i++){
var list = document.getElementById("list" + i);
list.onclick = function(){
txt.value = this.innerHTML;
clue.style.display = "none";
};
}
}
txt.onblur = function(){
clue.style.display = "none";
};
};
function createList(data){
var i, str='', len = data.length;
for(i = 0; i < len; i++){
str += '<li id="list'
+ i
+'">'
+ decodeURIComponent(data.pop());
+'</li>';
}
return str;
}