类实现百度模糊下拉框查询
实现百度模糊下拉框查询
需求:
- 根据用户输入的值实时查询数据显示在下拉框中
- 点击下拉框将值写入input并可以拿到对应项的数据
代码实现
class FuzzyQuery {
constructor(id) {
this.item = null; // 点击的某一项
this.app = document.getElementById(id); // 获取 input 的父容器
this.ul = document.createElement('ul'); // 创建 ul 元素
this.input = app.firstElementChild; // 获取 input 元素
// 模糊下拉框点击事件
this.ul.addEventListener('click', () => {
this.item = event.srcElement.item;
this.input.value = event.srcElement.innerText;
this.hide();
})
// 鼠标悬停颜色变化
this.ul.addEventListener('mouseover', () => {
event.srcElement.tagName === 'LI' ?
event.srcElement.style.backgroundColor = this.configure.hoverColor || '#EBEEF5' : '';
})
this.ul.addEventListener('mouseout', () => {
event.srcElement.tagName === 'LI' ?
event.srcElement.style.backgroundColor = this.configure.backgroundColor || '#fff' : '';
})
// 输入框焦点事件
this.input.addEventListener('focus', () => {
this.show();
})
this.input.addEventListener('blur', () => {
setTimeout(() => {
this.hide();
}, 300)
})
if (window.getComputedStyle(this.app).position === "static")
this.app.style.position = 'relative';
// 一次性设置多个 ul 元素的 css
this.ul.style.cssText =
`max-height: 300px;
overflow:auto;
position:absolute;
left:-1px;
margin:0;
padding:0;
top:${this.input.offsetHeight}px;
width:${this.input.offsetWidth}px;
border:2px solid #4e6ef2;
border-radius:8px;
z-index:99;`;
this.ul.style.backgroundColor = "#fff";
this.hide();
}
// 获取当前点击的某一项
get() {
return this.item || null;
}
// 写入模糊查询的数组和要显示的 key
set(array, value) {
this.ul.innerHTML = null;
array.forEach(item => {
const li = document.createElement('li');
li.style.cssText =
`listStyle:none;
paddingLeft:20px;
fontSize:17px;
height:${this.configure.itemHeight} || 21px;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;`;
li.innerText = item[value];
li.item = item;
this.ul.appendChild(li);
})
this.app.appendChild(this.ul);
}
// 配置
configure(term) {
this.configure = term;
this.ul.style.maxHeight = term.maxHeight || '300px';
this.ul.style.backgroundColor = term.backgroundColor|| '#fff';
}
// 模糊查询下拉框显示
show() {
this.ul.style.display = 'inline';
}
// 模糊查询下拉框显示
hide() {
this.ul.style.display = 'none';
}
}
调用方法
<div id="app">
<input type="text" />
</div>
// 对应input元素的父元素
const fuzzyQuery= new FuzzyQuery('app');
配置
fuzzyQuery.configure({
backgroundColor: 'red',
hoverColor: 'blue',
maxHeight: '100px',
});
写入模糊查询的数组和要显示的 key
// 放在ajax里,data是数组里面带对象的数据
fuzzyQuery.set(data,'key');
获取用户点击的某一项数据
fuzzyQuery.get();
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14451057.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?