DIV CSS 佈局教程網

用 JS 實作輸入框自動匹配字元的小範例
編輯:關於JavaScript     

這個範例示範如何在輸入框中即時比對並自動帶出符合的字元清單。不過要提醒的是,所有可匹配的字元必須事先寫好,如果是大型網站,大概就得靠資料庫的紀錄來動態提供。

html

複製程式碼 程式碼如下:

<style>
ul,li{margin: 0; padding: 0;width:100%;}
</style>
<script language="javascript" type="text/javascript">
function checkword()
{
   var wordvalue=document.getElementById("word").value.toLowerCase();
   var alltxt="all|big|cut|car|daph8|eeg|egg|eat|fix|good|hand|hidden|ill|jack|kevin|long|man|number|part|quit|QQ|rest|reg|set|submit|time|tag|view|windows|want|xy|xun|young|yuyu|z|David|哈哈|";//這裡就是你所想要匹配的字元,可惜只能用於小型論壇
   var alltxtpp=alltxt.toLowerCase();
   var alltxt_xiang=alltxt.split("|");
   var alltxt_xiang1=alltxtpp.split("|");
   var inhtml="<ul>"
   var isyou=0;
   for (i=0;i<alltxt_xiang1.length;i++)
   {
       if (alltxt_xiang1[i].substr(0,wordvalue.length)==wordvalue)
       {
            inhtml=inhtml+"<li onclick=\"document.getElementById('word').value=this.innerHTML;document.getElementById('showmenu').style.display='none';\" onmouseover=\"this.style.backgroundColor='#666666'\" onmouseout=\"this.style.backgroundColor=''\">"+alltxt_xiang[i]+"</li>";
            isyou=1;
       }
   }
   inhtml=inhtml+"</ul>";
   if (isyou==1)
   {
       document.getElementById("showmenu").innerHTML=inhtml;
       document.getElementById("showmenu").style.display="";
   }
   else
   {
       document.getElementById("showmenu").innerHTML="";
       document.getElementById("showmenu").style.display="none";
   }
   if (wordvalue=="")
   {
       document.getElementById("showmenu").innerHTML="";
       document.getElementById("showmenu").style.display="none";
   }
}
</script>
<input type="text" name="word" size="20" id="word" onkeyup="checkword()" style="border:1px solid #666666;width:200px;height:25px;">
<div style="position: absolute; width: 200px; height: 100px; z-index: 1; left: 10px; top: 40px;border:1px solid #666666;display:none;" id="showmenu"></div>

運作方式是:把候選字串以「|」分隔成陣列,在輸入框 keyup 時取出目前輸入值,逐一比對每個字串的開頭是否相符,符合的就拼成帶點擊與滑過效果的 li 元素塞進提示層;點擊任一項會把該值填回輸入框並隱藏清單,形成類似搜尋建議的自動補全效果。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved