参考代码
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>人人试题</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-size: 14px;
font-family: "Microsoft yahei";
}
.divCon {
width: 300px;
margin: 100px auto;
}
#string {
width: 200px;
height: 30px;
}
#strul {
width: 200px;
}
</style>
</head>
<body>
<form id="inform" name="inform" class="divCon" action="" method="post">
<input id="string" name="string" class="input" type="text/plain" value="" autocomplete="off"
/>
</form>
<ul id="strul">
</ul>
<script type="text/javascript">
window.onload = function () {
var frm = document.getElementById("inform");
var input = document.getElementById("string");
var ul = document.getElementById("strul");
function init() {
function keydownFn(e) {
if (e.which === 13) {
e.preventDefault();
}
}
input.addEventListener('keydown', keydownFn);
}
init();
ul.style.position = "absolute";
ul.style.top = (input.offsetTop + input.offsetHeight) + "px";
ul.style.left = input.offsetLeft + "px";
var arr = ["didiso", "aadidi", "aaa", "bdidi", "bblol", "bbbplp", "aaboko"];
var len = arr.length;
input.selectedIndex = -1;
input.focus();
input.onkeyup = function (event) {
ul.innerHTML = "";
ul.style.borderWidth = "1px";
ul.style.borderStyle = "solid";
ul.style.borderColor = "#999";
var value = input.value;
if (value) {
var reg = new RegExp("^" + value + "+");
for (var i = 0; i < len; i++) {
if (reg.test(arr[i])) {
var li = document.createElement("li");
var matchlen = value.length;
var string = arr[i].substr(matchlen);
li.innerHTML = "<strong>" + value + "</strong>" + string;
li.style.listStyle = "none";
ul.appendChild(li);
}
}
}
var li = document.getElementsByTagName("li");
for (var j = 0, lilen = li.length; j < lilen; j++) {
li[j].onmouseover = function () {
this.style.backgroundColor = "#ececec";
}
li[j].onmouseout = function () {
this.style.backgroundColor = "#fff";
}
li[j].onclick = function () {
input.value = this.innerText;
ul.innerHTML = "";
ul.style.border = "none";
}
}
input.options = li;
event = event || window.event;
switch (event.keyCode) {
case 38:
this.selectedIndex--;
if (this.selectedIndex < 0) {
this.selectedIndex = this.options.length - 1;
}
paintcolor(this);
break;
case 40:
this.selectedIndex++;
if (this.selectedIndex > this.options.length - 1) {
this.selectedIndex = 0;
}
paintcolor(this);
break;
case 13:
if (this.selectedIndex >= 0) {
var str = this.options[this.selectedIndex].textContent;
this.value = str;
}
ul.innerHTML = "";
ul.style.border = "none";
break;
}
}
}
function paintcolor(target) {
if (target.selectedIndex >= 0) {
target.options[target.selectedIndex].style.backgroundColor = "#ececec";
}
}
</script>
</body>
</html>
结果测试