案例:模拟百度搜索框
需求分析: 1.键盘松开txt : 根据搜索内容显示对应搜索列表ul 2.鼠标移入li元素:颜色变红 3.鼠标移出li元素:颜色变原先颜色 4.鼠标点击li元素: (1)搜索框显示点击的li元素文本 (2)情况内容列表ul 思路分析:事件三要素 1 获取元素: 2 注册事件: 3 事件处理:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>仿百度搜索</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-size: 20px;
}
.box {
width: 600px;
height: 40px;
margin: 200px auto;
position: relative;
}
#txt {
width: 498px;
height: 38px;
border: 1px solid #ccc;
font-size: 20px;
}
#search {
width: 100px;
height: 40px;
}
#keywords {
position: absolute;
top: 40px;
left: 0;
background-color: rgb(12, 255, 24);
list-style: none;
width: 500px;
}
li {
line-height: 24px;
}
</style>
<script>
window.onload = function () {
const ul = document.querySelector("#keywords");
const txt = document.querySelector("#txt");
console.log(ul, txt);
txt.oninput = function () {
ul.innerHTML = "";
let value = this.value.trim();
if (value == "") return;
keywords.forEach(function (item) {
if (item.indexOf(value) != -1) {
const li = document.createElement("li");
li.innerText = item;
ul.appendChild(li);
li.onmouseover = function () {
this.style.backgroundColor = "red";
};
li.onmouseout = function () {
this.style.backgroundColor = "";
};
li.onclick = function () {
txt.value = item;
ul.innerHTML = "";
};
}
});
};
document.querySelector("#search").onclick = function () {
let value = txt.value.trim();
if (value.length == 0) return;
location.assign(`http://www.baidu.com/s?ie=UTF-8&wd=${value}`);
};
};
</script>
<script src="./js/data.js"></script>
</head>
<body>
<div class="box">
<div class="top"><input type="text" id="txt" /><input type="button" value="search" id="search" /></div>
<ul id="keywords"></ul>
</div>
</body>
</html>
|