百度一下自動提示js

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p id="box">
    <input type="text" id="txtSearch">
    <input type="button" value="百度一下" id="btnSearch">
</p>
</body>
</html>

CSS:

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;
}

JavaScript:

var datas = ["a", "abc", "abbbb", "abxxxx", "xyz", "abcdef", "abzzzz"];
var text = document.getElementById("txtSearch");
var btnSearch = document.getElementById("btnSearch");
text.onkeyup = function() {
    var val = this.value;
    var filterArr = [];
    for (var i = 0; i < datas.length; i++) {
        if (datas[i].indexOf(val) == 0) {
            filterArr.push(datas[i]);
        }
    }

    //3.改bug
    //3.1根據匹配數組創建結構之前先判斷一下頁面上是否已經存在pop瞭
    var popDiv = document.getElementById("pop");
    if (popDiv) {
        //如果進來瞭 說明已經有瞭 就要把他幹掉
        box.removeChild(popDiv);
    }
    //3.2如果沒有匹配項 就不要創建pop瞭
    if (filterArr.length === 0) {
        return;
    }
    //3.3如果是空字符串 就不創建瞭
    //if(val.length===0)
    if (val === "") {
        return;
    }

    var popDiv = document.createElement("p");
    popDiv.id = "pop";
    box.appendChild(popDiv);
    var ul = document.createElement("ul");
    popDiv.appendChild(ul);
    for (var i = 0; i < filterArr.length; i++) {
        var li = document.createElement("li");
        li.innerText = filterArr[i];
        ul.appendChild(li);
        li.onclick = function() {
            text.value = this.innerText;
            box.removeChild(popDiv);
        };
    }
}

發佈留言