日期:2014-05-17 浏览次数:20714 次
javascript 输入框自动提示 <!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> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> <style type="text/css"> .mouseOut{ background:#708090; color:#fffafa; } .mouseOver{ background:#fffafa; color:#000000; } </style> <script type="text/javascript"> var completeDiv; var inputField; var nameTable; var nameTableBody; var selectIndex; var tempInputValue; var suggest = new Array(); suggest[0] = "ab"; suggest[1] = "abc"; suggest[2] = "abcd"; function initVars(){ inputField = document.getElementById("names"); nameTable = document.getElementById("name_table"); completeDiv = document.getElementById("popup"); nameTableBody = document.getElementById("name_table_body"); } function findNames(){ var eventkey = window.event.keyCode; initVars(); if(eventkey == 27){ esc(); }else if(eventkey == 40 || eventkey == 38){ changeSelect(eventkey); }else{ selectIndex = -1; clearNames(); var inputValue = inputField.value; tempInputValue = inputValue; if(inputValue == null || inputValue == "") return; for(var i=0; i<suggest.length; i++){ if(suggest.indexOf(inputValue) == 0){ //alert(suggest.indexOf(inputValue)); setNames(inputValue, suggest); } } } } function esc(){ while(nameTableBody.childNodes.length > 0){ nameTableBody.removeChild(nameTableBody.firstChild); } completeDiv.style.border = "0px"; inputField.value = tempInputValue; } function changeSelect(eventkey){ var suggestSize = nameTableBody.childNodes.length; if(suggestSize == null || suggestSize == 0) return; if(eventkey == 40 && selectIndex < suggestSize - 1) selectIndex++; else if(eventkey == 38 && selectIndex > -1) selectIndex--; for(var i=0; i<suggestSize; i++){ if(selectIndex == -1){ nameTableBody.childNodes.style.backgroundColor = "#ffffff"; nameTableBody.childNodes.style.color = "#000000"; inputField.value = tempInputValue; }else if(i == selectIndex){ nameTableBody.childNodes.style.backgroundColor = "#000000"; nameTableBody.childNodes.style.color = "#ffffff"; inputField.value = nameTableBody.childNodes.childNodes[0].innerHTML; } else{ nameTableBody.childNodes.style.backgroundColor = "#ffffff"; nameTableBody.childNodes.style.color = "#000000"; } } } function clearNames(){ var ind = nameTableBody.childNodes.length; for(var i=ind-1; i>=0; i--){ nameTableBody.removeChild(nameTableBody.childNodes); } completeDiv.style.border = "none"; } function setNames(inputValue, txt){ setOffsets(); var row, cell, txtNode; var nextNode = txt; row = document.createElement("tr"); cell = document.createElement("td"); cell.onmouseout = function(){this.className = 'mouseOver';}; cell.onmouseover = function(){this.className = 'mouseOut'