效果图
输入时,根据输入内容实时显示提示内容,
失去焦点时,提示内容消失
再次获取焦点时,提示内容再次出现
注:鼠标划过或键盘上下键操作时,划过内容显示在输入框中功能,在
模拟下拉菜单中已实现,可根据“模拟下拉菜单”的写法进行添加,稍作修改。
html
<div id="search">
<input type="text">
<button>嗖嗖嗖~~</button>
<ul class="search-res"></ul>
</div>
CSS
<style>
* {
margin: 0;
padding: 0;
}
#search {
width: 600px;
margin: 0 auto;
margin-top: 300px;
position: relative;
}
#search input {
width: 480px;
height: 100%;
border: 1px solid #b6b6b6;
height: 20px;
padding: 9px 7px;
font: 16px arial;
border: 1px solid #b8b8b8;
border-bottom: 1px solid #ccc;
border-right: 0;
vertical-align: top;
outline: none;
box-shadow: none;
-webkit-appearance: textfield;
background-color: white;
-webkit-rtl-ordering: logical;
user-select: text;
}
#search button {
cursor: pointer;
box-sizing: border-box;
width: 97px;
height: 40px;
line-height: 38px;
padding: 0;
border: 0;
background: none;
background-color: #38f;
font-size: 16px;
color: white;
box-shadow: none;
font-weight: normal;
margin-left: -20px;
}
.result {
position: absolute;
padding: 9px 7px;
background: #ddd;
}
.search-res {
position: absolute;
top: 100%;
left: 0;
width: 480px;
border: 1px solid #b6b6b6;
border-top: none;
}
.search-res li {
list-style-type: none;
line-height: 20px;
padding: 2px 5px;
}
.ac {
display: none;
}
</style>
JS
<script>
//获取元素
let ul = '';
window.onload = function () {
//获取元素
let input = document.querySelector('input');
ul = document.querySelector('ul');
//输入框输入事件
input.oninput = function () {
//删除ul的ac类
ul.classList.remove('ac');
//实时获取输入值
jsonp(this.value);
}
//输入框失去焦点时,提示的下拉菜单消失
input.onblur = function () {
ul.classList.add('ac');
}
//输入框获得焦点时,提示的下拉菜单出现
input.onfocus = function () {
ul.classList.remove('ac');
}
}
function jsonp(data) {
// console.log(data);
//创建script节点
let script = document.createElement('script');
// console.log(script);
//设置script的src属性为百度接口
script.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + data + "&json=1&p=3&sid=22084_1436_13548_21120_22036_22073&req=2&csor=0&cb=callback";
// console.log(script);
//追加到head中
document.head.appendChild(script);
//追加后删除
script.remove();
}
function callback(data) {
// console.log(data);
//结构赋值关键词
let { g } = data;
// console.log(g);
//创建一个空字符串用于拼接关键词
let html = '';
//循环遍历关键词字符串
g.forEach(e => {
html += `<li>${e.q}</li>`;
});
//将关键词提示追加到页面中
ul.innerHTML = html;
}
</script>