[关闭]
@52fhy 2015-07-27T10:45:49.000000Z 字数 9959 阅读 589

bigautocomplete实现联想输入,自动补全

JavaScript JS插件


bigautocomplete是一款Jquery插件。用它实现仿搜索引擎文本框自动补全插件功能很实用,使用也很简单,引入了插件之后写几行代码就可以实现,可以灵活设置。

先看效果图:

效果图

上图是通过ajax请求服务器返回的数据。下面简单介绍如何使用。

一、如何使用

引入jquery.bigautocomplete.jsjquery.bigautocomplete.css文件到你的页面中。

二、参数说明

  1. $("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代码:

  1. <input type="text" id="tt" value="" class="text" />

javascript代码:

  1. $(function(){
  2. $("#tt").bigAutocomplete({
  3. width:543,
  4. data:[{title:"中国好声音",result:{ff:"qq"}},
  5. {title:"中国移动网上营业厅"},
  6. {title:"中国银行"},
  7. {title:"中国移动"},
  8. {title:"中国好声音第三期"},
  9. {title:"中国好声音 第一期"},
  10. {title:"中国电信网上营业厅"},
  11. {title:"中国工商银行"},
  12. {title:"中国好声音第二期"},
  13. {title:"中国地图"}],
  14. callback:function(data){
  15. alert(data.title);
  16. }
  17. });
  18. })

js中data里的result可以不写。

2、ajax请求:

html代码:

  1. <input type="text" id="company" value="" class="text" />

javascript代码:

  1. $(function(){
  2. $("#tt").bigAutocomplete({
  3. width:543,
  4. url:'http://localhost/test/suggestCom',
  5. callback:function(data){
  6. //alert(data.title);
  7. }
  8. });
  9. })

服务端返回数据格式:

  1. {"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示例)

  1. public function suggestCom(){
  2. $wd = $_POST['keyword'];
  3. $keywords = $wd;
  4. $company_model = M('Company');
  5. $res = $company_model->where("name like '%".$keywords."%' or abbr like '%".$keywords."%' ")->limit(10)->select();
  6. foreach($res as $v){
  7. $suggestions[]= array('title' => $v['name']);
  8. }
  9. echo json_encode(array('data' => $suggestions));
  10. }

默认是POST过来的数据,名称是keyword,返回数据是和本地data一致的。


附上jquery.bigautocomplete.js和jquery.bigautocomplete.css文件代码:

jquery.bigautocomplete.js

  1. (function($){
  2. var bigAutocomplete = new function(){
  3. this.currentInputText = null;//目前获得光标的输入框(解决一个页面多个输入框绑定自动补全功能)
  4. 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];//键盘上功能键键值数组
  5. this.holdText = null;//输入框中原始输入的内容
  6. //初始化插入自动补全div,并在document注册mousedown,点击非div区域隐藏div
  7. this.init = function(){
  8. $("body").append("<div id='bigAutocompleteContent' class='bigautocomplete-layout'></div>");
  9. $(document).bind('mousedown',function(event){
  10. var $target = $(event.target);
  11. if((!($target.parents().andSelf().is('#bigAutocompleteContent'))) && (!$target.is(bigAutocomplete.currentInputText))){
  12. bigAutocomplete.hideAutocomplete();
  13. }
  14. })
  15. //鼠标悬停时选中当前行
  16. $("#bigAutocompleteContent").delegate("tr", "mouseover", function() {
  17. $("#bigAutocompleteContent tr").removeClass("ct");
  18. $(this).addClass("ct");
  19. }).delegate("tr", "mouseout", function() {
  20. $("#bigAutocompleteContent tr").removeClass("ct");
  21. });
  22. //单击选中行后,选中行内容设置到输入框中,并执行callback函数
  23. $("#bigAutocompleteContent").delegate("tr", "click", function() {
  24. bigAutocomplete.currentInputText.val( $(this).find("div:last").html());
  25. var callback_ = bigAutocomplete.currentInputText.data("config").callback;
  26. if($("#bigAutocompleteContent").css("display") != "none" && callback_ && $.isFunction(callback_)){
  27. callback_($(this).data("jsonData"));
  28. }
  29. bigAutocomplete.hideAutocomplete();
  30. })
  31. }
  32. this.autocomplete = function(param){
  33. if($("body").length > 0 && $("#bigAutocompleteContent").length <= 0){
  34. bigAutocomplete.init();//初始化信息
  35. }
  36. var $this = $(this);//为绑定自动补全功能的输入框jquery对象
  37. var $bigAutocompleteContent = $("#bigAutocompleteContent");
  38. this.config = {
  39. //width:下拉框的宽度,默认使用输入框宽度
  40. width:$this.outerWidth() - 2,
  41. //url:格式url:""用来ajax后台获取数据,返回的数据格式为data参数一样
  42. url:null,
  43. /*data:格式{data:[{title:null,result:{}},{title:null,result:{}}]}
  44. url和data参数只有一个生效,data优先*/
  45. data:null,
  46. //callback:选中行后按回车或单击时回调的函数
  47. callback:null};
  48. $.extend(this.config,param);
  49. $this.data("config",this.config);
  50. //输入框keydown事件
  51. $this.keydown(function(event) {
  52. switch (event.keyCode) {
  53. case 40://向下键
  54. if($bigAutocompleteContent.css("display") == "none")return;
  55. var $nextSiblingTr = $bigAutocompleteContent.find(".ct");
  56. if($nextSiblingTr.length <= 0){//没有选中行时,选中第一行
  57. $nextSiblingTr = $bigAutocompleteContent.find("tr:first");
  58. }else{
  59. $nextSiblingTr = $nextSiblingTr.next();
  60. }
  61. $bigAutocompleteContent.find("tr").removeClass("ct");
  62. if($nextSiblingTr.length > 0){//有下一行时(不是最后一行)
  63. $nextSiblingTr.addClass("ct");//选中的行加背景
  64. $this.val($nextSiblingTr.find("div:last").html());//选中行内容设置到输入框中
  65. //div滚动到选中的行,jquery-1.6.1 $nextSiblingTr.offset().top 有bug,数值有问题
  66. $bigAutocompleteContent.scrollTop($nextSiblingTr[0].offsetTop - $bigAutocompleteContent.height() + $nextSiblingTr.height() );
  67. }else{
  68. $this.val(bigAutocomplete.holdText);//输入框显示用户原始输入的值
  69. }
  70. break;
  71. case 38://向上键
  72. if($bigAutocompleteContent.css("display") == "none")return;
  73. var $previousSiblingTr = $bigAutocompleteContent.find(".ct");
  74. if($previousSiblingTr.length <= 0){//没有选中行时,选中最后一行行
  75. $previousSiblingTr = $bigAutocompleteContent.find("tr:last");
  76. }else{
  77. $previousSiblingTr = $previousSiblingTr.prev();
  78. }
  79. $bigAutocompleteContent.find("tr").removeClass("ct");
  80. if($previousSiblingTr.length > 0){//有上一行时(不是第一行)
  81. $previousSiblingTr.addClass("ct");//选中的行加背景
  82. $this.val($previousSiblingTr.find("div:last").html());//选中行内容设置到输入框中
  83. //div滚动到选中的行,jquery-1.6.1 $$previousSiblingTr.offset().top 有bug,数值有问题
  84. $bigAutocompleteContent.scrollTop($previousSiblingTr[0].offsetTop - $bigAutocompleteContent.height() + $previousSiblingTr.height());
  85. }else{
  86. $this.val(bigAutocomplete.holdText);//输入框显示用户原始输入的值
  87. }
  88. break;
  89. case 27://ESC键隐藏下拉框
  90. bigAutocomplete.hideAutocomplete();
  91. break;
  92. }
  93. });
  94. //输入框keyup事件
  95. $this.keyup(function(event) {
  96. var k = event.keyCode;
  97. var ctrl = event.ctrlKey;
  98. var isFunctionalKey = false;//按下的键是否是功能键
  99. for(var i=0;i<bigAutocomplete.functionalKeyArray.length;i++){
  100. if(k == bigAutocomplete.functionalKeyArray[i]){
  101. isFunctionalKey = true;
  102. break;
  103. }
  104. }
  105. //k键值不是功能键或是ctrl+c、ctrl+x时才触发自动补全功能
  106. if(!isFunctionalKey && (!ctrl || (ctrl && k == 67) || (ctrl && k == 88)) ){
  107. var config = $this.data("config");
  108. var offset = $this.offset();
  109. $bigAutocompleteContent.width(config.width);
  110. var h = $this.outerHeight() - 1;
  111. $bigAutocompleteContent.css({"top":offset.top + h,"left":offset.left});
  112. var data = config.data;
  113. var url = config.url;
  114. var keyword_ = $.trim($this.val());
  115. if(keyword_ == null || keyword_ == ""){
  116. bigAutocomplete.hideAutocomplete();
  117. return;
  118. }
  119. if(data != null && $.isArray(data) ){
  120. var data_ = new Array();
  121. for(var i=0;i<data.length;i++){
  122. if(data[i].title.indexOf(keyword_) > -1){
  123. data_.push(data[i]);
  124. }
  125. }
  126. makeContAndShow(data_);
  127. }else if(url != null && url != ""){//ajax请求数据
  128. $.post(url,{keyword:keyword_},function(result){
  129. makeContAndShow(result.data)
  130. },"json")
  131. }
  132. bigAutocomplete.holdText = $this.val();
  133. }
  134. //回车键
  135. if(k == 13){
  136. var callback_ = $this.data("config").callback;
  137. if($bigAutocompleteContent.css("display") != "none"){
  138. if(callback_ && $.isFunction(callback_)){
  139. callback_($bigAutocompleteContent.find(".ct").data("jsonData"));
  140. }
  141. $bigAutocompleteContent.hide();
  142. }
  143. }
  144. });
  145. //组装下拉框html内容并显示
  146. function makeContAndShow(data_){
  147. if(data_ == null || data_.length <=0 ){
  148. return;
  149. }
  150. var cont = "<table><tbody>";
  151. for(var i=0;i<data_.length;i++){
  152. cont += "<tr><td><div>" + data_[i].title + "</div></td></tr>"
  153. }
  154. cont += "</tbody></table>";
  155. $bigAutocompleteContent.html(cont);
  156. $bigAutocompleteContent.show();
  157. //每行tr绑定数据,返回给回调函数
  158. $bigAutocompleteContent.find("tr").each(function(index){
  159. $(this).data("jsonData",data_[index]);
  160. })
  161. }
  162. //输入框focus事件
  163. $this.focus(function(){
  164. bigAutocomplete.currentInputText = $this;
  165. });
  166. }
  167. //隐藏下拉框
  168. this.hideAutocomplete = function(){
  169. var $bigAutocompleteContent = $("#bigAutocompleteContent");
  170. if($bigAutocompleteContent.css("display") != "none"){
  171. $bigAutocompleteContent.find("tr").removeClass("ct");
  172. $bigAutocompleteContent.hide();
  173. }
  174. }
  175. };
  176. $.fn.bigAutocomplete = bigAutocomplete.autocomplete;
  177. })(jQuery)

jquery.bigautocomplete.css

  1. @charset "utf-8";
  2. .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;}
  3. .bigautocomplete-layout table{border-collapse:collapse;border-spacing:0;background:none repeat scroll 0 0 #FFFFFF;width:100%;cursor:default;}
  4. .bigautocomplete-layout table tr{background:none repeat scroll 0 0 #FFFFFF;}
  5. .bigautocomplete-layout .ct{background:none repeat scroll 0 0 #D2DEE8 !important;}
  6. .bigautocomplete-layout div{word-wrap:break-word;word-break:break-all;padding:1px 5px;}

css经过改写,以适应某些情况不兼容的bug。

页面html代码:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Jquery实现仿搜索引擎文本框自动补全插件</title>
  6. <script src="js/jquery-1.7.min.js" type="text/javascript"></script>
  7. <script src="js/bigautocomplete/jquery.bigautocomplete.js?v=2"></script>
  8. <link rel="stylesheet" href="css/bigautocomplete/jquery.bigautocomplete.css" type="text/css" />
  9. <script type="text/javascript">
  10. $(function(){
  11. $("#tt").bigAutocomplete({
  12. width:543,
  13. url:'__MODULE__/test/suggestCom',
  14. callback:function(data){
  15. //alert(data.title);
  16. }
  17. });
  18. })
  19. </script>
  20. </head>
  21. <body>
  22. <style type="text/css">
  23. *{margin:0;padding:0;list-style-type:none;}
  24. a,img{border:0;}
  25. .demo{width:720px;margin:30px auto;}
  26. .demo h2{font-size:16px;color:#3366cc;height:30px;}
  27. .demo li{float:left;}
  28. .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;}
  29. .button{width:95px;height:32px;padding:0;padding-top:2px\9;border:0;background-position:0 -35px;background-color:#ddd;cursor:pointer}
  30. </style>
  31. <div class="demo">
  32. <h2>bigautocomplete联想输入测试</h2>
  33. <form action="" method="post" name="searchform" id="searchform" class="searchinfo">
  34. <ul>
  35. <li><input type="text" id="tt" value="" class="text" /></li>
  36. <li><input type="submit" value="搜索" class="button" /></li>
  37. </ul>
  38. </form>
  39. </div>
  40. </body>
  41. </html>

转自:
bigautocomplete实现联想输入,自动补全 - 飞鸿影~ - 博客园
http://www.cnblogs.com/52fhy/p/4455988.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注