本例以顏色為例,為使用者提供自動提示,展示效果和運行結果
1、建立架構結構:
複製代碼 代碼如下:
<body>
<form method="post" name="myForm1">
Color: <input type="text" name="colors" id="colors" onkeyup="findColors();" />
</form>
<div id="popup">
<ul id="colors_ul"></ul>
</div>
</body>
2、頁面和表單CSS:
複製代碼 代碼如下:
<style>
<!--
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px; padding:0px; margin:5px; form{padding:0px; margin:0px;}
input{ font-family:Arial, Helvetica, sans-serif;
font-size:12px; border:1px solid #000000;
width:200px; padding:1px; margin:0px; #popup{ position:absolute; width:202px;
color:#004a7e; font-size:12px;
font-family:Arial, Helvetica, sans-serif;
left:41px; top:25px; #popup.show{ border:1px solid #004a7e; #popup.hide{ border:none;
} ul{
list-style:none;
margin:0px; padding:0px; li.mouseOver{
background-color:#004a7e;
color:#FFFFFF; li.mouseOut{
background-color:#FFFFFF;
color:#004a7e; -->
</style>
3、實現JS匹配使用者輸入:
複製代碼 代碼如下:
<script language="javascript">
var oInputField; //考慮到很多函數中都要使用
var oPopDiv; //因此採用全域變數的形式
var oColorsUl;
var aColors = ["red","green","blue","magenta","yellow",……"ivory","darkmagenta","cornfloewrblue"];
aColors.sort(); //按字母排序,使顯示結果更友好
function initVars(){ oInputField = document.forms["myForm1"].colors;
oPopDiv = document.getElementByIdx_x("popup");
oColorsUl = document.getElementByIdx_x("colors_ul"); function clearColors(){ for(var i=oColorsUl.childNodes.length-1;i>=0;i--)
oColorsUl.removeChild(oColorsUl.childNodes[i]);
oPopDiv.className = "hide"; function setColors(the_colors){ clearColors(); //每輸入一個字母就先清除原先的提示,再繼續
oPopDiv.className = "show";
var oLi;
for(var i=0;i<the_colors.length;i++){ oLi = document.createElement_x("li");
oColorsUl.appendChild(oLi);
oLi.appendChild(document.createTextNode(the_colors[i]));
oLi. = function(){
this.className = "mouseOver"; //滑鼠經過時高亮 oLi. = function(){
this.className = "mouseOut"; //離開時恢複原樣 oLi.onclick = function(){ oInputField.value = this.firstChild.nodeValue;
clearColors(); //同時清除提示框 } function findColors(){
initVars(); //初始設定變數
if(oInputField.value.length > 0){
var aResult = new Array(); //用於存放匹配結果
for(var i=0;i<aColors.length;i++) //從顏色表中找匹配的顏色 if(aColors[i].indexOf(oInputField.value) == 0)
aResult.push(aColors[i]); //壓入結果
if(aResult.length>0) //如果有匹配的顏色則顯示出來
setColors(aResult);
else //否則清除,使用者多輸入一個字母
clearColors(); //就有可能從有匹配到無,到無的時候需要清除 else
clearColors(); //無輸入時清除提示框(例如使用者按del鍵)
</script>
文字框輸入提示/自動完成的Js代碼
文字框輸入自動匹配或提示的功能,輸入內容,自動匹配對應資料,可用上下鍵控制選項、按斷行符號鍵選擇,也可以直接用滑鼠選擇。代碼:建立執行個體,第一個參數是執行個體對象的名稱,第二個是最多顯示的數量。
<!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>文字框輸入提示/自動完成功能</title> <meta http-equiv="content-type" content="text/html;charset=gb2312"> </head> <body> 友情提示:文字框屏蔽了斷行符號,因此斷行符號鍵暫不可用。 </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]