DIV CSS 佈局教程網

用 JS 實作輸入框自動匹配提示的小例子
編輯:JavaScript綜合知識     

搜尋框在打字時即時跳出匹配的關鍵字提示,是很常見的便利功能。本文示範如何用原生 JavaScript 實作這樣一個「輸入框自動匹配字符」的小例子。

先來看它的限制:這個示範把所有可匹配的字符事先寫死在程式碼裡,因此只適合小型論壇或 demo。若是大型網站,匹配資料自然應該來自資料庫,透過 AJAX 即時查詢。理解這個前提後,我們來看程式碼:

<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|long|man|number|part|quit|QQ|rest|set|submit|time|tag|view|windows|want|young|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>

這段程式碼的運作流程是這樣的:使用者在輸入框打字時觸發 onkeyup 事件呼叫 checkword(),函數先取得輸入值並轉小寫,然後把預先定義、以「|」分隔的字串 split 成陣列,逐一比對每個詞的開頭是否與輸入相符(用 substr 截取相同長度來比較)。凡是匹配的詞,就動態拼湊成帶有點擊與滑鼠移入效果的 li 元素,塞進提示層 showmenu 裡顯示;若無匹配或輸入為空,則把提示層隱藏起來。

每個提示項都綁定了 onclick,點一下就能把該詞填回輸入框並收起提示,滑鼠移過時還會高亮背景,互動相當順手。若想把它升級成真正的線上應用,只要把寫死的字串替換成 AJAX 向後端查詢的結果即可,整體框架幾乎不用改動。

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