这是一个帮助您入门的免费图书馆解决方案。
您可能希望添加在文本框获得或失去焦点时隐藏和显示 div 的事件。也许 [esc] 应该清除选择?(我没有在ie中测试过)
<style>div.active{ background: red }</style>
<input type="text" id="tb">
<div id="Parent">
<div id="childOne">ChildOne </div>
<div id="childOne">ChildTwo </div>
<div id="childOne">ChildThree </div>
<div id="childOne">ChildFour </div>
</div>
<script type="text/javascript">
function autocomplete( textBoxId, containerDivId ) {
var ac = this;
this.textbox = document.getElementById(textBoxId);
this.div = document.getElementById(containerDivId);
this.list = this.div.getElementsByTagName('div');
this.pointer = null;
this.textbox.onkeydown = function( e ) {
e = e || window.event;
switch( e.keyCode ) {
case 38: //up
ac.selectDiv(-1);
break;
case 40: //down
ac.selectDiv(1);
break;
}
}
this.selectDiv = function( inc ) {
if( this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length ) {
this.list[this.pointer].className = '';
this.pointer += inc;
this.list[this.pointer].className = 'active';
this.textbox.value = this.list[this.pointer].innerHTML;
}
if( this.pointer === null ) {
this.pointer = 0;
this.list[this.pointer].className = 'active';
this.textbox.value = this.list[this.pointer].innerHTML;
}
}
}
new autocomplete( 'tb', 'Parent' );
</script>