效果图
![](https://i-blog.csdnimg.cn/direct/617200a147bc46678b032eadef6c9fc3.gif)
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>练习:小米搜索框案例(焦点事件)</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
list-style: none;
}
.box {
margin: 50px auto;
width: 223px;
}
.box input {
padding: 0 10px;
width: 223px;
height: 48px;
border: 1px solid #e0e0e0;
/* 去除元素在获得焦点时显示的轮廓线,
否则看不出获得焦点时的橙色边框线效果 */
outline: none;
}
/* 获得焦点 */
.box input:focus {
border: 1px solid #ff6700;
}
.box ul {
display: none;
border: 1px solid #ff6700;
border-top: none;
}
.box ul li a {
display: block;
padding: 6px 15px;
font-size: 12px;
color: #424242;
text-decoration: none;
}
.box ul li a:hover {
background-color: #eeeeee;
}
</style>
</head>
<body>
<div class="box">
<input type="search" placeholder="小米11">
<ul>
<li><a href="#">全部商品</a></li>
<li><a href="#">小米11</a></li>
<li><a href="#">小米10S</a></li>
<li><a href="#">小米笔记本</a></li>
<li><a href="#">小米手机</a></li>
<li><a href="#">黑鲨4</a></li>
<li><a href="#">空调</a></li>
</ul>
</div>
<script>
const input = document.querySelector(".box input")
const ul = document.querySelector(".box ul")
// 获得焦点
input.addEventListener("focus", () => {
ul.style.display = "block"
})
// 失去焦点
input.addEventListener("blur", () => {
ul.style.display = "none"
})
</script>
</body>
</html>