文字框輸入內容實現智慧提示效果程式碼例項

antzone發表於2017-04-06

本章節分享一段程式碼例項,它實現了文字框輸入內容能夠實現智慧提示效果。

在谷歌和百度這樣的搜尋引擎都是先了這樣的功能,大家輸入關鍵詞的時候,下面會出現一些相關的推薦,非常的人性化,下面就是一段程式碼,需要的朋友可以做一下參考,程式碼如下:

前端程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>螞蟻部落</title>
<style type="text/css" media="screen">
  body
  {
   font: 11px arial;
  }
  .suggest_link
  {
   width:120px;
   background-color: #FFFFFF;
   padding: 2px 6px 2px 6px;
  }
  .suggest_link_over
  {
   width:120px;
   background-color: #E8F2FE;
   padding: 2px 6px 2px 6px;
  }
  #suggestResult
  {
   position: absolute;
   background-color: #FFFFFF;
   text-align: left;
   border: 1px solid #000000;
  }
  /*input*/
  .input_on
  {
   padding: 2px 8px 0pt 3px;
   height: 18px;
   border: 1px solid #999;
   background-color: #FFFFCC;
  }
  .input_off
  {
   padding: 2px 8px 0pt 3px;
   height: 18px;
   border: 1px solid #CCC;
   background-color: #FFF;
  }
  .input_move
  {
   padding: 2px 8px 0pt 3px;
   height: 18px;
   border: 1px solid #999;
   background-color: #FFFFCC;
  }
  .input_out
  {
   /*height:16px;預設高度*/
   padding: 2px 8px 0pt 3px;
   height: 18px;
   border: 1px solid #CCC;
   background-color: #FFF;
  }
</style>
<script language="javascript" type="text/javascript">
  var $ = document.getElementById;
  //建立XMLHttpRequest物件  
  function createXMLHttpRequest() {
   var obj;
   if (window.XMLHttpRequest) { //Mozilla 瀏覽器
    obj = new XMLHttpRequest();
   }
   else if (window.ActiveXObject) { // IE瀏覽器
    try {
     obj = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
     try {
      obj = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (e) { }
    }
   }
   return obj;
  }
  //當輸入框的內容變化時,呼叫該函式
  function searchSuggest() {
   var inputField = $("txtSearch");
   var suggestText = $("suggestResult");
   if (inputField.value.length > 0) {
    var o = createXMLHttpRequest();
    var url = "SearchResult.ashx?searchText=" + escape(inputField.value);
    o.open("GET", url, true);
    o.onreadystatechange = function () {
     if (o.readyState == 4) {
      if (o.status == 200) {
       var sourceItems = o.responseText.split("\n");
       if (sourceItems.length > 1) {
        suggestText.style.display = "";
        suggestText.innerHTML = "";
        for (var i = 0; i < sourceItems.length - 1; i++) {
         var sourceText = sourceItems[i].split("@")[1];
         var sourceValue = sourceItems[i].split("@")[0];
         var s = "<div onmouseover=\"javascript:suggestOver(this);\" ";
         s += " onmouseout=\"javascript:suggestOut(this);\" ";
         s += " onclick=\"javascript:setSearch('" + sourceText + "','" + sourceValue + "');\" ";
         s += " class=\"suggest_link\" >" + sourceText + "</div>";
         suggestText.innerHTML += s;
        }
       }
       else {
        suggestText.style.display = "none";
       }
      }
     }
    }; //指定響應函式
    o.send(null); // 傳送請求
   }
   else {
    suggestText.style.display = "none";
   }
  }
  function delayExecute() {
   $("valueResult").value = "";
   window.setTimeout(function () { searchSuggest() }, 800);
   //延時處理
  }
  function suggestOver(div_value) {
   div_value.className = "suggest_link_over";
  }
  function suggestOut(div_value) {
   div_value.className = "suggest_link";
  }
  function setSearch(a, b) {
   $("txtSearch").value = a;
   $("valueResult").value = b;
   var div = $("suggestResult");
   div.innerHTML = "";
   div.style.display = "none";
  }
  function showResult() {
   alert($("txtSearch").value + $("valueResult").value);
  }
</script>
</head>
<body>
<form id="form1" action="">
  <input type="text" id="txtSearch" name="txtSearch" onkeyup="delayExecute();" size="20"
    class="input_out" onfocus="this.className='input_on';this.onmouseout=''"
    onblur="this.className='input_off';this.onmouseout=function(){this.className='input_out'};"
    onmousemove="this.className='input_move'" onmouseout="this.className='input_out'" />
  <input type="hidden" id="valueResult" name="valueResult" value="" />
  <br />
  <div id="suggestResult" style="display: none"></div>
  <br/>
  <input id="button1" type="button" value="提交" onclick="showResult();" />
</form>
</body>
</html>

伺服器端程式碼,c#編寫:

[C#] 純文字檢視 複製程式碼
<%@ WebHandler Language="C#" Class="SearchResult" %>
using System;
using System.Web;
using System.Data;
public class SearchResult : IHttpHandler {
 public void ProcessRequest (HttpContext context) {
  object QueryWord=context.Request.QueryString["searchText"];
  if (QueryWord != null)
  {
   if (QueryWord.ToString().Trim().Length > 0)
   {
    DataTable dt = getDB();
    string returnText = "";
    if (dt != null && dt.Rows.Count > 0)
    {
     DataRow[] dr = dt.Select(" name like '%" + QueryWord .ToString()+ "%' ");
     if (dr.Length > 0)
     {
      for (int i = 0; i < dr.Length; i++)
      {
       //可設定返回多字串
       returnText += dr[i]["id"].ToString() + "@" + dr[i]["name"].ToString() + "\n";
      }
     }
    }
    context.Response.Write(returnText);
    context.Response.End();
   }
  }  
 }
 public bool IsReusable {
  get {
   return false;
  }
 }
 /// <summary>
 /// 獲取資料來源的方法
 /// </summary>
 /// <returns>資料來源</returns>
 private DataTable getDB()
 {
  DataTable dt = new DataTable();
  dt.Columns.Add("id");
  dt.Columns.Add("name");
  dt.Columns.Add("age");
  dt.Rows.Add(new object[] { "000001", "張三", "26" });
  dt.Rows.Add(new object[] { "000002", "張曉", "26" });
  dt.Rows.Add(new object[] { "000003", "張嵐", "27" });
  dt.Rows.Add(new object[] { "000004", "李四", "25" });
  dt.Rows.Add(new object[] { "000005", "李星", "27" });
  return dt;
 }
}

相關文章