web学习笔记13-移动端搜索框提示功能

    最近项目一直在迭代更新,说忙也不算忙,说不忙也还挺忙的,没有什么新的东西做,所以拿出来一个搜索的小模块分享下,功能就是输入关键字能出来相关字的联想吧,删除一些字的时候顺带可以保存上一段的联想,从外观上来看,效果还罢了,这里分享给大家,可以供大家看看。最近也在初步学习nodejs的基础,虽然之前写过node相关的,但是现在再看这些,感觉有点懵。不过这些以后再写文说吧。

    搜索功能效果图如下,github链接在此search_demo

9月-05-2017 16-32-02.gif

按照老规矩,下面就直接写编写过程了

第一步:创建文件

    创建相应的html,js,css文件,引入jquery。

图片.png

第二步:引入文件,设置meta,编写html以及样式

html:

<!DOCTYPE html> <html lang="en"> <head>     <!--通用媒体查询-->     <meta charset="UTF-8" />     <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1, maximum-scale=1" />     <link rel="stylesheet" href="search.css">     <title>搜索</title> </head> <body> <div class="search_nav">     <input type="search" class="search_input searchProduct" placeholder="查找您需要的商品">     <div class="search_cancel">取消</div> </div> <div class="search_find">     <div class="search_history">         历史搜索     </div>     <div class="search_find_line">        <!--搜索结果和搜索历史-->     </div> </div>  <script src="jquery.js"></script> <script src="search.js" type="application/javascript"></script> </body> </html> 

css:

 *{     margin: 0;     padding: 0; } body{     background-color: #f5f5f9; } .search_nav{     width: 100%;     height: 45px;     position: fixed;     top:0;     left: 0;     background-color: #20232b; } .search_input{     float: left;     width: 75%;     height: 35px;     margin-left: 30px;     margin-top: 5px;     font-size: 15px;     text-indent: 30px;     /*border: none;*/     border: 1px solid black;     border-radius: 40px;     outline: none; } input::-webkit-search-cancel-button {display: none;} .search_cancel{     float: right;     width: 15%;     height: 100%;     color:white;     text-align: center;     line-height: 45px;     /*background-color: lightblue;*/ } .search_find{     background:#fff;     line-height:42px;     margin-top: 45px; } .search_history{     padding-left:10px;     font-weight:700;     font-size:16px } .search_find_title{     display:block;     /*margin-top: 45px;*/     position:relative;     padding-left:15px;     padding-right:10px;     font-size:14px;     color:#8a8a8a;     width:100%;     box-sizing:border-box } .search_find_title:after{     content:'';     position:absolute;     top:0;     left:15px;     box-sizing:border-box;     width:92%;     height:1px;     color:#ddd;     border-bottom:1px solid #ddd;     -webkit-transform-origin:0 0;     transform-origin:0 0;     -webkit-transform:scaleY(.4);     transform:scaleY(.4) }   

    当然了,这里面的样式格局什么的在自己实际项目中需要根据自己的项目来调整,不需要跟我这写的一样,重要的是逻辑部分。

第三步:编写js逻辑

    一般情况下,我们在进入搜索页面的时候,大多数会出现历史搜索,也就是搜索记录,我们首先需要的就是进行历史搜索的渲染,我这里历史搜索都是用localStorage进行存储,大家根据需要可以进行对应的存储或者获取。

var history_search = [];//存储历史搜索数据  //获取历史搜索数据,若没有则为空 if(localStorage.getItem("history_search")){     history_search = JSON.parse(localStorage.getItem("history_search"));//获取历史搜索数据 }else{     history_search = []; } 

    接下来在获取了历史记录的前提下,我们要把历史记录渲染到页面上

//渲染历史记录 function setpage(){     var product_list = '';     //动态添加元素至页面上     if(history_search.length != 0){         $(".search_history").show();         if(history_search.length >= 10){             for(var i = 0; i < 10 ;i++){                 product_list = '<a class="search_find_title">'+history_search[i]+'</a>';                 $(".search_find_line").append(product_list);             }         }else{             for(var i = 0; i < history_search.length;i++){                 product_list = '<a class="search_find_title">'+history_search[i]+'</a>';                 $(".search_find_line").append(product_list);             }         }     }else{         $(".search_history").hide();     } } setpage(); 

    这里我们需要注意的是,一般的历史记录不会是太多的,一般会显示前十条最近搜索的,我这边在渲染的时候做了截取,其实在存的时候就应该去做判断,在超出10条或者规定条数的时候我们只保存十条或者规定条数,然后在渲染的时候就不需要再去截取了。

    接下来需要做的处理就是在输入关键字的时候,一些请求和缓存搜索出来的提示数据

var obj_arr = [];//请求结果 var timeout = 0; var keyName = '';//搜索关键字 var ajaxCache = {};//定义缓存对象(保存请求出来的数据) 

    这里我先把另外两个方法先提出来先写了,一个是渲染页面的方法,一个是判断字符串是否为空的方法,这两个方法在接下来的逻辑中需要调用。

//渲染页面方法 function setListPage(obj,no){     console.log(obj);     console.log(no);     ajaxCache = {};     obj_arr = obj;     $(".search_find_line").empty();     if(no == 1){         $(".search_history").hide();     }else{         $(".search_history").show();     }      var search_res = '';     for(var i = 0; i < obj.length;i++){         search_res = '<a class="search_find_title">'+obj[i]+'</a>';         $(".search_find_line").append(search_res);     } }  //判断字符串是不是为空 function isNull( str ){     if ( str == "" ) return true;     var regu = "^[ ]+$";     var re = new RegExp(regu);     return re.test(str); } 

    这里就是最重要的一部分了。

//当按钮被松开时,触发事件 $('.searchProduct').keyup(function(evt){ //获取到关键字     keyName = $(this).val(); //判断关键字是否为空     if(isNull(keyName) == false || keyName != ''){         //若输入字符串不为空,则显示网络请求搜索。         clearTimeout(timeout);         timeout = setTimeout(function(){             if(!!ajaxCache[keyName]){                 //显示自动提示框,给框里填关联词条的内容                 setListPage(ajaxCache[keyName],1);                 ajaxCache = {};             }else{                 var sendData = {                     "keyName":keyName                 };                  $.ajax({                     type: "POST",                     url: url,//我们自个的接口没法公开,大
家可以用自己的。                     data:JSON.stringify(sendData),                     dataType: 'json',                     success: function (data) {                         console.log(data);                         if(data){                             if(data.data){                                 //显示自动提示框,给框里填关联词条的内容                                 ajaxCache[keyName]=[];                                 ajaxCache[keyName]=data.data;//给缓存对象赋值                                 setListPage(data.data,1);                             }                         }                     },                     error: function (err) {                         console.log(err);                     }                 });             }         },200);     }else{         //若输入字符串为空,则显示历史搜索。         ajaxCache = {};         if(history_search.length == 0){             //若数组为空,历史搜索不显示             $(".search_history").hide();         }else{             $(".search_history").show();             setListPage(history_search,2)         }     } //手机端按下右下角的搜索按钮的时候触发事件    if (evt.keyCode == 13) {         localStorage.setItem('search_keyName',keyName);         var count = 0;         //判断历史搜索中是否已经存在当前搜索的关键字         for(var j = 0; j < history_search.length;j++){             if(keyName == history_search[j]){                 count += 1;             }else{                 count += 0;             }         }         //如果没有,则添加进历史搜索         if(count == 0){             history_search.unshift(keyName);         }         //这边缺少的处理是历史搜索排序的问题。         localStorage.setItem("history_search",JSON.stringify(history_search));         window.location.href="";//跳转到搜索结果页之类的页面     } 

    这就基本完成了,这里没有加一个搜索结果页,在出现提示搜索的时候,应该在<a class="search_find_title"></a>上添加点击事件,以跳转到搜索结果页之类的,这边可以根据自己的需求来处理。
    这上面的流程基本上就能编写出移动端搜索功能,要是有什么问题可以留言探讨。