今天寫了個小demo,利用本地存儲的特點,模擬百度搜索框。
主要知識是利用本地存儲的特點,模擬百度搜索時的歷史記錄顯示。
主要HTML代碼為
<div class="search"> <input type="text"/> <button class="btn">搜索</button> </div> <ul class="hidden"> <li></li> </ul>
CSS代碼為:
1 .search{ 2 margin:30px 80px; 3 position: relative; 4 5 } 6 .search input{ 7 position: absolute; 8 top:0; 9 left:0; 10 width: 300px; 11 height:35px; 12 outline:none; 13 border:1px solid #979797; 14 text-indent: 10px; 15 } 16 .search .btn{ 17 position: absolute; 18 top:0; 19 left:301px; 20 width:80px; 21 height:37px; 22 border:1px solid #979797; 23 background:linear-gradient(to bottom ,#f9f9f9, #ededed); 24 font-size:16px; 25 outline: none; 26 27 } 28 ul{ 29 width: 381px; 30 border:1px solid #979797; 31 position: absolute; 32 top: 66px; 33 left:80px; 35 box-sizing: border-box; 36 } 37 ul li{ 38 line-height: 30px; 39 color:#7a77c8; 40 cursor: pointer; 41 padding:0 10px; 42 box-sizing: border-box; 43 } 44 ul li:hover{ 45 background:#7a77c8; 46 color:white; 47 } 48 .hidden{ 49 display: none; 50 } 51 .show{ 52 display: block; 53 }
JavaScript部分及注釋為:
1 <!-- 獲取本地數據--> 2 3 // var data=localStorage.getItem('search'); 4 // console.log(data); 5 6 // 獲取表單元素 7 var text=document.getElementsByTagName('input')[0]; 8 9 //獲取用來顯示歷史記錄的列表框 10 var hidden=document.getElementsByTagName('ul')[0]; 11 12 // 獲取搜索按鈕 13 var btn=document.getElementsByClassName('btn')[0]; 14 15 16 17 // 從本地存儲中獲取本地數據 18 var data=localStorage.getItem('search'); 19 //將數據轉換為數組格式 20 data=data?JSON.parse(data):[]; 21 22 23 // 當鍵盤按鍵釋放時觸發事件 24 25 text.onkeyup= function () { 26 27 // 獲取輸入的數據 28 var txt=text.value; 29 30 // 初始化一個變量用來承載查找到的數據 31 var html=''; 32 33 for(var i=0;i<data.length;i++){ 34 var reg=new RegExp(txt); //只有用構造函數方式才能傳遞參數 35 36 var index= data[i].search(reg); //在本地數據中查找是否含有輸入的內容 37 38 // 如果有,則將數據放到變量中 39 if(index!=-1){ 40 html+=' <li>'+data[i]+'</li>'; 41 42 } 43 } 44 45 // 將最后得到的所有數據添加到要展示的列表框中 46 hidden.innerHTML=html; 47 // 顯示列表框 48 hidden.className=' show'; 49 50 51 }; 52 53 // 給搜索框添加單擊事件,當事件發生時,將表單中需要搜索的內容添加到本地存儲起來, 54 btn.onclick= function () { 55 56 var txt=text.value; 57 58 // 先判斷本地是否存在,不存在添加, 59 if(data.indexOf(txt)==-1){ 60 61 data.push(txt); 62 } 63 64 // 更新本地存儲的數據 65 localStorage.setItem('search',JSON.stringify(data)); 66 67 // 搜索后 將表單內容置空,將選擇框隱藏 68 text.value=''; 69 hidden.className='hidden'; 70 71 location.href='https://www.baidu.com/s?word='+txt; 72 73 }; 74 75 76 // 給歷史展示框添加單擊事件,利用事件委托 77 // 將點擊的歷史展示框中 的內容添加到搜索欄中, 78 hidden.onclick= function (e) { 79 80 var li= e.target; 81 82 var title=li.innerHTML; 83 84 console.log(title); 85 86 text.value=title; 87 88 }
剛剛學習了本地存儲,利用它的特點寫個小demo。
方便與喜歡前端的小伙伴互相學習。如果有覺得不太好的地方,歡迎提出。
最后,生命不息,奮斗不止!