js實現百度淘寶搜尋功能
阿新 • • 發佈:2020-02-19
本文例項為大家分享了js實現百度淘寶搜尋功能的具體程式碼,供大家參考,具體內容如下
由於沒有後臺數據,用陣列模擬一下後臺返回的資料
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box{ width:214px; /*height: 400px;*/ margin: 100px auto; position: relative; } </style> </head> <body> <div class="box"> <input type="text" id="txt"> <input type="button" id="btn" value="搜尋"> </div> <script src="common.js"></script> <script> //模擬後臺的資料 var keyWords = [ "一馬當先","一箭雙鵰","一絲不苟","一心二用","吃火鍋","吃雞肉","吃雞腿","吃雞蛋","哈1哈","嘻1嘻","嗚1嗚",]; //給文字框註冊鍵盤松開事件 $query("#txt").onkeyup = function () { var txt = $query("#txt").value; if ($query(".box div")) { $query(".box").removeChild($query(".box div")); } if (txt.length == 0) { if ($query(".box div")) { $query(".box").removeChild($query(".box div")); } return; } var newArr = []; for (var i = 0; i < keyWords.length; i++) { if (keyWords[i].indexOf(txt) !=-1) { newArr.push(keyWords[i]); } } if (newArr.length > 0) { var newBox = document.createElement("div"); newBox.style.border = "1px solid red"; newBox.style.width = "100%"; $query(".box").appendChild(newBox); for (var j = 0; j < newArr.length; j++) { var newP = document.createElement("p"); newP.style.width = "100%"; newP.innerText = newArr[j]; newP.onmouseover = function () { this.style.backgroundColor = "yellow"; } newP.onmouseout = function () { this.style.backgroundColor = ""; } newBox.appendChild(newP); } } console.log(newArr);//列印匹配的資料 } </script> </body> </html>
最後,附上效果圖,確實醜了點?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。