类实现百度模糊下拉框查询

实现百度模糊下拉框查询

需求:

  • 根据用户输入的值实时查询数据显示在下拉框中
  • 点击下拉框将值写入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();
posted @ 2021-02-26 10:39  懒惰ing  阅读(198)  评论(0编辑  收藏  举报