bigautocomplete是一款Jquery插件。用它實現仿搜索引擎文本框自動補全插件功能很實用,使用也很簡單,引入了插件之后寫幾行代碼就可以實現,可以靈活設置。
先看效果圖:
上圖是通過ajax請求服務器返回的數據。下面簡單介紹如何使用。
一、如何使用:
引入jquery.bigautocomplete.js和jquery.bigautocomplete.css文件到你的頁面中。
二、參數說明:
$("xxxxx").bigAutocomplete({data:[...],url:"",width:0,callback:{}})
參數 | 說明 |
data(可選): |
data:格式{data:[{title:null,result:{}},{title:null,result:{}}]}
url和data兩個參數必須有一個,且只有一個生效,data優先。
|
url(可選): | url為字符串,用來ajax后台獲取數據,返回的數據格式為data參數一樣。 |
width(可選): | 下拉框的寬度,默認使用輸入框寬度。 |
callback(可選): | 選中行后按回車或單擊時回調的函數,用於返回選中行的其他數據及做一些操作。 |
三、示例:
1、本地數據:
html代碼:
<input type="text" id="tt" value="" class="text" />
javascript代碼:
$(function(){ $("#tt").bigAutocomplete({ width:543, data:[{title:"中國好聲音",result:{ff:"qq"}}, {title:"中國移動網上營業廳"}, {title:"中國銀行"}, {title:"中國移動"}, {title:"中國好聲音第三期"}, {title:"中國好聲音 第一期"}, {title:"中國電信網上營業廳"}, {title:"中國工商銀行"}, {title:"中國好聲音第二期"}, {title:"中國地圖"}], callback:function(data){ alert(data.title); } }); })
js中data里的result可以不寫。
2、ajax請求:
html代碼:
<input type="text" id="company" value="" class="text" />
javascript代碼:
$(function(){ $("#tt").bigAutocomplete({ width:543, url:'http://localhost/test/suggestCom', callback:function(data){ //alert(data.title); } }); })
服務端返回數據格式:
{"data":[{"title":"\u5317\u4eac\u73b0\u4ee3"},{"title":"\u5317\u4eac\u57ce\u5efa\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u5efa\u5de5\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u9996\u90fd\u65c5\u6e38\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u533b\u836f\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u4e00\u8f7b\u63a7\u80a1\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u91d1\u9685\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u71d5\u4eac\u5564\u9152\u96c6\u56e2\u516c\u53f8"},{"title":"\u5317\u4eac\u5e02\u71c3\u6c14\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u4f4f\u603b\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"}]}
服務端的代碼:(以ThinkPHP示例)
public function suggestCom(){ $wd = $_POST['keyword']; $keywords = $wd; $company_model = M('Company'); $res = $company_model->where("name like '%".$keywords."%' or abbr like '%".$keywords."%' ")->limit(10)->select(); foreach($res as $v){ $suggestions[]= array('title' => $v['name']); } echo json_encode(array('data' => $suggestions)); }
默認是POST過來的數據,名稱是keyword,返回數據是和本地data一致的。
附上jquery.bigautocomplete.js和jquery.bigautocomplete.css文件代碼:
jquery.bigautocomplete.js

(function($){ var bigAutocomplete = new function(){ this.currentInputText = null;//目前獲得光標的輸入框(解決一個頁面多個輸入框綁定自動補全功能) this.functionalKeyArray = [9,20,13,16,17,18,91,92,93,45,36,33,34,35,37,39,112,113,114,115,116,117,118,119,120,121,122,123,144,19,145,40,38,27];//鍵盤上功能鍵鍵值數組 this.holdText = null;//輸入框中原始輸入的內容 //初始化插入自動補全div,並在document注冊mousedown,點擊非div區域隱藏div this.init = function(){ $("body").append("<div id='bigAutocompleteContent' class='bigautocomplete-layout'></div>"); $(document).bind('mousedown',function(event){ var $target = $(event.target); if((!($target.parents().andSelf().is('#bigAutocompleteContent'))) && (!$target.is(bigAutocomplete.currentInputText))){ bigAutocomplete.hideAutocomplete(); } }) //鼠標懸停時選中當前行 $("#bigAutocompleteContent").delegate("tr", "mouseover", function() { $("#bigAutocompleteContent tr").removeClass("ct"); $(this).addClass("ct"); }).delegate("tr", "mouseout", function() { $("#bigAutocompleteContent tr").removeClass("ct"); }); //單擊選中行后,選中行內容設置到輸入框中,並執行callback函數 $("#bigAutocompleteContent").delegate("tr", "click", function() { bigAutocomplete.currentInputText.val( $(this).find("div:last").html()); var callback_ = bigAutocomplete.currentInputText.data("config").callback; if($("#bigAutocompleteContent").css("display") != "none" && callback_ && $.isFunction(callback_)){ callback_($(this).data("jsonData")); } bigAutocomplete.hideAutocomplete(); }) } this.autocomplete = function(param){ if($("body").length > 0 && $("#bigAutocompleteContent").length <= 0){ bigAutocomplete.init();//初始化信息 } var $this = $(this);//為綁定自動補全功能的輸入框jquery對象 var $bigAutocompleteContent = $("#bigAutocompleteContent"); this.config = { //width:下拉框的寬度,默認使用輸入框寬度 width:$this.outerWidth() - 2, //url:格式url:""用來ajax后台獲取數據,返回的數據格式為data參數一樣 url:null, /*data:格式{data:[{title:null,result:{}},{title:null,result:{}}]} url和data參數只有一個生效,data優先*/ data:null, //callback:選中行后按回車或單擊時回調的函數 callback:null}; $.extend(this.config,param); $this.data("config",this.config); //輸入框keydown事件 $this.keydown(function(event) { switch (event.keyCode) { case 40://向下鍵 if($bigAutocompleteContent.css("display") == "none")return; var $nextSiblingTr = $bigAutocompleteContent.find(".ct"); if($nextSiblingTr.length <= 0){//沒有選中行時,選中第一行 $nextSiblingTr = $bigAutocompleteContent.find("tr:first"); }else{ $nextSiblingTr = $nextSiblingTr.next(); } $bigAutocompleteContent.find("tr").removeClass("ct"); if($nextSiblingTr.length > 0){//有下一行時(不是最后一行) $nextSiblingTr.addClass("ct");//選中的行加背景 $this.val($nextSiblingTr.find("div:last").html());//選中行內容設置到輸入框中 //div滾動到選中的行,jquery-1.6.1 $nextSiblingTr.offset().top 有bug,數值有問題 $bigAutocompleteContent.scrollTop($nextSiblingTr[0].offsetTop - $bigAutocompleteContent.height() + $nextSiblingTr.height() ); }else{ $this.val(bigAutocomplete.holdText);//輸入框顯示用戶原始輸入的值 } break; case 38://向上鍵 if($bigAutocompleteContent.css("display") == "none")return; var $previousSiblingTr = $bigAutocompleteContent.find(".ct"); if($previousSiblingTr.length <= 0){//沒有選中行時,選中最后一行行 $previousSiblingTr = $bigAutocompleteContent.find("tr:last"); }else{ $previousSiblingTr = $previousSiblingTr.prev(); } $bigAutocompleteContent.find("tr").removeClass("ct"); if($previousSiblingTr.length > 0){//有上一行時(不是第一行) $previousSiblingTr.addClass("ct");//選中的行加背景 $this.val($previousSiblingTr.find("div:last").html());//選中行內容設置到輸入框中 //div滾動到選中的行,jquery-1.6.1 $$previousSiblingTr.offset().top 有bug,數值有問題 $bigAutocompleteContent.scrollTop($previousSiblingTr[0].offsetTop - $bigAutocompleteContent.height() + $previousSiblingTr.height()); }else{ $this.val(bigAutocomplete.holdText);//輸入框顯示用戶原始輸入的值 } break; case 27://ESC鍵隱藏下拉框 bigAutocomplete.hideAutocomplete(); break; } }); //輸入框keyup事件 $this.keyup(function(event) { var k = event.keyCode; var ctrl = event.ctrlKey; var isFunctionalKey = false;//按下的鍵是否是功能鍵 for(var i=0;i<bigAutocomplete.functionalKeyArray.length;i++){ if(k == bigAutocomplete.functionalKeyArray[i]){ isFunctionalKey = true; break; } } //k鍵值不是功能鍵或是ctrl+c、ctrl+x時才觸發自動補全功能 if(!isFunctionalKey && (!ctrl || (ctrl && k == 67) || (ctrl && k == 88)) ){ var config = $this.data("config"); var offset = $this.offset(); $bigAutocompleteContent.width(config.width); var h = $this.outerHeight() - 1; $bigAutocompleteContent.css({"top":offset.top + h,"left":offset.left}); var data = config.data; var url = config.url; var keyword_ = $.trim($this.val()); if(keyword_ == null || keyword_ == ""){ bigAutocomplete.hideAutocomplete(); return; } if(data != null && $.isArray(data) ){ var data_ = new Array(); for(var i=0;i<data.length;i++){ if(data[i].title.indexOf(keyword_) > -1){ data_.push(data[i]); } } makeContAndShow(data_); }else if(url != null && url != ""){//ajax請求數據 $.post(url,{keyword:keyword_},function(result){ makeContAndShow(result.data) },"json") } bigAutocomplete.holdText = $this.val(); } //回車鍵 if(k == 13){ var callback_ = $this.data("config").callback; if($bigAutocompleteContent.css("display") != "none"){ if(callback_ && $.isFunction(callback_)){ callback_($bigAutocompleteContent.find(".ct").data("jsonData")); } $bigAutocompleteContent.hide(); } } }); //組裝下拉框html內容並顯示 function makeContAndShow(data_){ if(data_ == null || data_.length <=0 ){ return; } var cont = "<table><tbody>"; for(var i=0;i<data_.length;i++){ cont += "<tr><td><div>" + data_[i].title + "</div></td></tr>" } cont += "</tbody></table>"; $bigAutocompleteContent.html(cont); $bigAutocompleteContent.show(); //每行tr綁定數據,返回給回調函數 $bigAutocompleteContent.find("tr").each(function(index){ $(this).data("jsonData",data_[index]); }) } //輸入框focus事件 $this.focus(function(){ bigAutocomplete.currentInputText = $this; }); } //隱藏下拉框 this.hideAutocomplete = function(){ var $bigAutocompleteContent = $("#bigAutocompleteContent"); if($bigAutocompleteContent.css("display") != "none"){ $bigAutocompleteContent.find("tr").removeClass("ct"); $bigAutocompleteContent.hide(); } } }; $.fn.bigAutocomplete = bigAutocomplete.autocomplete; })(jQuery)
jquery.bigautocomplete.css

@charset "utf-8"; .bigautocomplete-layout{display:none;background-color:#FFFFFF;border:1px solid #BCBCBC;position:absolute;z-index:9999 !important;max-height:220px;overflow-x:hidden;overflow-y:auto; text-align:left;} .bigautocomplete-layout table{border-collapse:collapse;border-spacing:0;background:none repeat scroll 0 0 #FFFFFF;width:100%;cursor:default;} .bigautocomplete-layout table tr{background:none repeat scroll 0 0 #FFFFFF;} .bigautocomplete-layout .ct{background:none repeat scroll 0 0 #D2DEE8 !important;} .bigautocomplete-layout div{word-wrap:break-word;word-break:break-all;padding:1px 5px;}
css經過改寫,以適應某些情況不兼容的bug。
頁面html代碼:

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Jquery實現仿搜索引擎文本框自動補全插件</title> <script src="js/jquery-1.7.min.js" type="text/javascript"></script> <script src="js/bigautocomplete/jquery.bigautocomplete.js?v=2"></script> <link rel="stylesheet" href="css/bigautocomplete/jquery.bigautocomplete.css" type="text/css" /> <script type="text/javascript"> $(function(){ $("#tt").bigAutocomplete({ width:543, url:'__MODULE__/test/suggestCom', callback:function(data){ //alert(data.title); } }); }) </script> </head> <body> <style type="text/css"> *{margin:0;padding:0;list-style-type:none;} a,img{border:0;} .demo{width:720px;margin:30px auto;} .demo h2{font-size:16px;color:#3366cc;height:30px;} .demo li{float:left;} .text{width:529px;height:22px;padding:4px 7px;padding:6px 7px 2px\9;font:16px arial;border:1px solid #cdcdcd;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top;outline:none;margin:0 5px 0 0;} .button{width:95px;height:32px;padding:0;padding-top:2px\9;border:0;background-position:0 -35px;background-color:#ddd;cursor:pointer} </style> <div class="demo"> <h2>bigautocomplete聯想輸入測試</h2> <form action="" method="post" name="searchform" id="searchform" class="searchinfo"> <ul> <li><input type="text" id="tt" value="" class="text" /></li> <li><input type="submit" value="搜索" class="button" /></li> </ul> </form> </div> </body> </html>