Recently work needs to do a search box, similar to Baidu's search box, need to achieve two functions:
1. Enter keywords to show the matching drop-down list
2. Select the matching item and find out the relevant content
General e-commerce site also often use the search bar, the first analysis of the implementation of the function, the input keyword immediately display a list of matches, the function input box to bind the "input" event, and then send an asynchronous request to the background to show the data on the page. Use the mouse or the up and down keys to select a match, click the search or the "Enter" key to search for specific results. Here we use two asynchronous requests, the first one to request a match, and the second to request a search result. Keyboard, mouse and input box events are to listen to, but also to consider the flexibility, that is, to adapt to a variety of similar needs, want to do a good job or some difficulty, the following distribution to achieve.
I. HTML and CSS
< Body > < ID= "Search-form"></div></ Body>
<style type= "Text/css" > *{margin:0;padding:0;List-style:None;Border:None;}Body{font-family:"Microsoft Yahei"!important;Background-color:#FDFFE0; }: Focus{Outline:None; }#search-form{position:relative;Top:50px;Display:inline; }</style>
Two. Import CSS and JS files
Because the blog cannot upload files, you can go to my git:http://git.oschina.net/manliu.com/search_frame on the complete project file
Three. Page reference JS
<script type= "Text/javascript" >varproposals = [' Baidu 1 ', ' Baidu 2 ', ' Baidu 3 ', ' Baidu 4 ', ' Baidu 5 ', ' Baidu 6 ', ' Baidu 7 ', ' 17 material net ', ' Baidu ', ' Sina '];$ (document). Ready (function(){ $(' #search-form '). Complete ({searchin:function(Val) {//incoming input value, return matching value /*var reg =/^[\u4f00-\u9fa5\uf900-\ufa2d]/; Return Reg.test (Val); */ varWord = "^" +val+ ". *"; varrs = []; $.each (Proposals,function(i,n) {if(N.match (Word)) {Rs.push (n); } }); returnrs; }, Width:400, Height:30, Submitin:function(text) {//Search for selected valuesalert (text); } });});</script>
Here the Searchin method is used to return the match, usually in the inside to define an asynchronous request, back to the background to fetch data, return an array, for the complex also need to modify the source code; Submitin is used to search for matching results, and can generally be asynchronous or synchronous requests.
jquery implements a search box similar to Baidu