<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>模擬百度搜索框</title>
<meta charset="utf-8" />
<style>
fieldset, img, input, button {
border: none;
padding: 0;
margin: 0;
outline-style: none;
}
ul, ol {
list-style: none;
margin: 0px;
padding: 0px;
}
#box {
width: 405px;
margin: 200px auto;
position: relative;
}
#txtSearch {
float: left;
width: 300px;
height: 32px;
padding-left: 4px;
border: 1px solid #b6b6b6;
border-right: 0;
}
#btnSearch {
float: left;
width: 100px;
height: 34px;
font: 400 14px/34px "microsoft yahei";
color: white;
background: #3385ff;
cursor: pointer;
}
#btnSearch:hover {
background: #317ef3;
}
#pop {
width: 303px;
border: 1px solid #ccc;
padding: 0px;
position: absolute;
top: 34px;
}
#pop ul li {
padding-left: 5px;
}
#pop ul li:hover {
background-color: #CCC;
}
</style>
</head>
<body>
<div class="clound-news-search" id="box"><input id="provinces" type="text" placeholder="搜索您想要了解的省份政策">
<button
class="btn btn-enter" οnclick="mymethon()">進入
</button>
</div>
<script type="text/javascript>
var box=document.getElementById("box");
var inp = document.getElementById("provinces");
var arr = ["a","ab","abc","abcd","aa","aaa"];
//綁定事件(輸入內容,鍵盤彈起事件)
inp.onkeyup = function () {
//創建一個字符串,添加相對應的內容
var newArr = [];
//我要從數組中查詢以input中輸入內容爲開頭的信息,然後添加到li中,轉換成字符串。
//遍歷老數組,然後判斷每一項,哪項是以input內容爲開頭的穿件一個li,塞進去。
for (var i = 0; i < arr.length; i++) {
//判斷當前項,是否已input內容爲開頭
//獲取輸入內容input標籤的value屬性值。
var val = this.value;
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(val) >= 0) {
newArr.push("<li class='arrLi' >" + arr[i] + "</li>");
}
}
}
var str = newArr.join("");
//Bug1.每次創建新的ul之前,先刪除舊的ul
//只有ul存在我們才能刪除ul
if (box.children[2]) {
//只要存在,那麼就是object,object類型的數據,只要不是null,對應的boolean值都是true;
box.removeChild(box.children[2]);
}
if (this.value.length === 0 || newArr.length === 0) {
//切斷函數(不在產生新的ul)
return;
}
//3.書寫事件驅動程序
var ul = document.createElement("ul");
//把創建好的內容添加到ul中。
ul.innerHTML = str;
box.appendChild(ul);
//給模擬引擎設置hover屬性 var list = document.getElementsByClassName("arrLi"); for (var i = 0; i < list.length; i++) { //爲li註冊鼠標進入事件 list[i].onmouseover = function () { //設置其背景顏色爲黃色 this.style.backgroundColor = "red"; }; //爲li註冊鼠標離開事件 list[i].onmouseout = function () { //恢復到這個標籤默認的顏色 this.style.backgroundColor = ""; }; } ;
}
</script>
</body>
</html>