<!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> </head> <style> body { background-color: #000; } #box { width: 600px; margin: 200px auto; } #txt { float: left; width: 300px; height: 30px; padding-left: 4px; border: 1px solid #b6b6b6; border-right: 0; } #pop ul { width: 300px; margin: 10px; padding: 0; list-style-type: none; } #btn { float: left; width: 100px; height: 34px; font: 400 14px/34px "microsoft yahei"; color: white; background: #3385ff; border: none; cursor: pointer; } #btn:hover { background: #317ef3; } </style> <body> <div id="box"> <input type="text" id="txt"> <input type="button" value="百度一下" id="btn"> </div> <script> function zy$(id) { return document.getElementById(id) }; var keyWords = ["妖精的尾巴再出新篇章", "宫崎骏老爷子复出", "次元墙破裂", "夏目友人帐第六季完结", "妖大音频怪物", "犬夜叉", "夏日大作战", "加勒比海盗五上映" ]; //先获取文本框,注册键盘抬起事件 zy$("txt").onkeyup = function () { //只要键盘抬起就判断.页面中是否存在这个div,如果存在则干掉 if (zy$("dv")) { zy$("box").removeChild(zy$("dv")); } //先获取文本框的值 var text = this.value; //创建一个临时数组,保存和数组中匹配的字符串 var tempArr = []; //和数组中的每个元素字符串进行对比 for (var i = 0; i < keyWords.length; i++) { if (keyWords[i].indexOf(text) == 0) { tempArr.push(keyWords[i]); } } //如果文本框中没有数据或者临时数组中没有数据,就没有必要创建div if (this.value.length == 0 || tempArr.length == 0) { //如果有div就删除 if (zy$("dv")) { zy$("box").removeChild(zy$("dv")); } return; } //创建一个div,然后在div中显示对应的内容 var dvObj = document.createElement("div"); dvObj.id = "dv"; zy$("box").appendChild(dvObj); //设置样式 dvObj.style.width = "302px"; dvObj.style.border = "1px solid #ccc"; //dvObj.style.height = "100px"; //在div中创建p标签,在p标签中显示临时数组中的数据 for (var j = 0; j < tempArr.length; j++) { var pobj = document.createElement("p"); dvObj.appendChild(pobj); pobj.innerHTML = tempArr[j]; pobj.style.color = "#fff"; pobj.style.width = "300px"; pobj.style.margin = "0"; pobj.style.padding = "0"; pobj.style.marginLeft = "5px"; pobj.style.marginTop = "5px"; pobj.style.cursor = "pointer"; pobj.style.fontSize = "20px"; //注册鼠标进入和鼠标离开事件 pobj.onmouseover = function () { this.style.backgroundColor = "rgba(255,255,255,.5)"; }; pobj.onmouseout = function () { this.style.backgroundColor = ""; }; pobj.onclick = function () { zy$("txt").value = this.innerText; this.parentNode.parentNode.removeChild(this.parentNode); }; } }; </script> </body> </html>