一、源碼
<!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> #txt { width: 350px; } div p { margin: 0; padding: 0; padding-left: 5px; padding-top: 5px; } </style> </head> <body> <div id="box"> <input type="text" placeholder="搜索" id="txt" value="" /> <input type="button" value="搜索" id="btn" /> </div> <script src="./js/common.js"></script> <script> var keywords = ["蘋果", "香蕉", "水晶梨", "景甜瓜", "火龍果", "西瓜", "芒果", "油桃", "哈密瓜", "紅提", "巨峰", "丑橘", "聖女果", "香梨", "香瓜", "水蜜桃", "油田"]; var tempArr = []; //臨時數組 my$("txt").onkeyup = function () { var text = this.value; // 判斷是否存在下拉框,存在刪除, if (my$("dv")) { my$("box").removeChild(my$("dv")); } else { // Do-nothing } // 臨時數組初始化,處理臨時數組數據 tempArr = []; for (let i = 0; i < keywords.length; i++) { if ((0 == keywords[i].indexOf(text)) && (0 != text.length)) { tempArr.push(keywords[i]); } else { // Do-nothing } } // 文本框是空的,臨時數組也是空的,不用創建div if (this.value.length == 0 || tempArr.length == 0) { // 如果頁面中又這個div,刪除這個div if (my$("dv")) { my$("box").removeChild(my$("dv")); } return; } // 創建div,把div加入到id="box"的標簽中 var dvObj = document.createElement("div"); my$("box").appendChild(dvObj); dvObj.id = "dv"; dvObj.style.width = "350px"; dvObj.style.border = "1px solid green"; // 遍歷tempArr數組,創建p,添加到dvObj里面 for (let i = 0; i < tempArr.length; i++) { var pObj = document.createElement("p"); // pObj.innerHTML = tempArr[i]; // 在p標簽內部添加文本文字 setInnerText(pObj,tempArr[i]); dvObj.appendChild(pObj); // 注冊鼠標進入事件,鼠標進入,添加黃色背景圖 pObj.onmouseover = function () { this.style.backgroundColor = "yellow"; }; // 注冊鼠標移除事件,鼠標移除,移除背景色 pObj.onmouseout = function () { this.style.backgroundColor = ""; }; } } </script> </body> </html>
二、common.js
/*根據id獲取元素對象*/ function my$(id){ return document.getElementById(id); } /** * 設置任意元素的中間文本內容 * @param {*} element 標簽元素 * @param {*} text 文本內容 */ function setInnerText(element,text){ if(typeof element.textContent === "undefined"){ element.innerText = text; }else{ element.textContent = text; } }
三、效果圖
初始圖:
輸入搜索內容:
鼠標懸停:
完善搜索內容:
清空搜索內容: