js实现获取焦点显示百度的输入框效果 失去焦点则隐藏
时间: 2023-11-17 22:06:39 浏览: 111
jQuery实现input输入框获取焦点与失去焦点时提示的消失与显示功能示例
5星 · 资源好评率100%
可以通过监听输入框的 focus 和 blur 事件来实现获取焦点显示、失去焦点隐藏的效果,具体代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>百度输入框</title>
<style>
#search-box {
position: relative;
width: 400px;
height: 30px;
margin: 0 auto;
margin-top: 100px;
}
#search-input {
width: 100%;
height: 100%;
padding: 0 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 15px;
outline: none;
box-sizing: border-box;
}
#search-suggest {
position: absolute;
top: 30px;
left: 0;
width: 400px;
max-height: 200px;
overflow: auto;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
display: none;
}
#search-suggest ul {
list-style: none;
margin: 0;
padding: 0;
}
#search-suggest li {
height: 30px;
line-height: 30px;
padding: 0 10px;
cursor: pointer;
}
#search-suggest li:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="search-box">
<input type="text" id="search-input" placeholder="输入搜索内容">
<div id="search-suggest"></div>
</div>
<script>
var searchInput = document.getElementById('search-input');
var searchSuggest = document.getElementById('search-suggest');
searchInput.addEventListener('focus', function() {
searchSuggest.style.display = 'block';
});
searchInput.addEventListener('blur', function() {
searchSuggest.style.display = 'none';
});
</script>
</body>
</html>
```
通过监听输入框的 focus 和 blur 事件,当输入框获取焦点时,显示搜索建议框,当输入框失去焦点时,隐藏搜索建议框。搜索建议框使用绝对定位实现,并设置了最大高度和滚动条。
阅读全文