输入框自动联想功能demo

思路:

简单来看,是创建一个输入框,然后给输入框绑定事件.当事件触发后,在输入框的正下方生成一个临时的选择列表.选中列表后,将数据回写到输入框,列表消失.

下面是从网上找的两种实现方式的demo,至于哪种好用,根据自身情况来考虑

第一种,使用工具类,比如jquery-ui.js

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>jQuery UI 自动完成(Autocomplete) - 默认功能</title>
		<link rel="stylesheet" href="css/jquery-ui.css">
		<script src="js/jquery-3.3.1.min.js"></script>
		<script src="js/jquery-ui.js"></script>
		<!--<link rel="style.css">-->
		<style>
			body {
				font-family: Arial, Helvetica, sans-serif;
			}
			
			table {
				font-size: 1em;
			}
			
			.ui-draggable,
			.ui-droppable {
				background-position: top;
			}
			
			.ui-autocomplete {
				max-height: 220px;
				overflow-y: auto;
				/* 防止水平滚动条 */
				overflow-x: hidden;
			}
		</style>
		<script>
			$(function() {

				/*jQuery.ajax({
					type: "post",
					async: false,
					url: "",
					dataType: "json",
					success: function(data) {
						res = data;
						$("#tags").autocomplete({
							source: res,
							//定义至少输入几个字符就可以查询
							minLength: 2
						});
					}
				});*/
				var res = ["妹喜", "妲己", "褒姒", "齐姜", "夏姬", "西施", "赵姬", "虞美人", "卓文君", "赵飞燕", "王昭君", "貂蝉", "大乔", "二乔", "绿珠", "祝英台", "苏小小", "张丽华", "蔡文姬", "谢道韫", "甄宓", "李祖娥", "武则天", "上官婉儿", "太平公主", "孙窈娘", "杨玉环", "关盼盼", "李师师", "杜十娘", "陈圆圆", "董小婉", "柳如是", "李香君"]

				$("#tags").autocomplete({
					source: res,
					//定义至少输入几个字
					minLength: 1
				});
			});
		</script>
	</head>

	<body>
		<div class="ui-widget">
			<label for="tags">标签:</label >
			<input id="tags">
		</div>
	</body>

</html>
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>自动填充二</title>
		<link rel="stylesheet" href="css/jquery-ui.css">
		<script src="js/jquery-3.3.1.min.js"></script>
		<script src="js/jquery-ui.js"></script>
		<!--<link rel="style.css">-->
		<style>
			body {
				font-family: Arial, Helvetica, sans-serif;
			}
			
			table {
				font-size: 1em;
			}
			
			.ui-draggable,
			.ui-droppable {
				background-position: top;
			}
			
			.ui-autocomplete {
				max-height: 220px;
				overflow-y: auto;
				/* 防止水平滚动条 */
				overflow-x: hidden;
			}
		</style>
		<script>
			$(function() {

				/*jQuery.ajax({
					type: "post",
					async: false,
					url: "",
					dataType: "json",
					success: function(data) {
						res = data;
						$("#tags").autocomplete({
							source: res,
							//定义至少输入几个字符就可以查询
							minLength: 2
						});
					}
				});*/
				var res = [{
						"label": "妹喜",
						"id":001,
						"desc":"夏亡背锅"
					}, {
						"label": "妲己",
						"id":002,
						"desc":"商亡背锅"
					}, {
						"label": "褒姒",
						"id":003,
						"desc":"西周亡背锅"
					}, {
						"label": "齐姜",
						"id":004,
						"desc":"齐国骨科"
					}, {
						"label": "夏姬",
						"id":005,
						"desc":"多人运动"
					}, {
						"label": "西施",
						"id":006,
						"desc":"沉鱼"
					}, {
						"label": "赵姬",
						"id":007,
						"desc":"千古一帝之母"
					}, {
						"label": "虞美人",
						"id":008,
						"desc":"四面楚歌"
					}, {
						"label": "卓文君",
						"id":009,
						"desc":"凤求凰一心人"
					}, {
						"label": "赵飞燕",
						"id":010,
						"desc":"卑人不可以为主"
					}, {
						"label": "王昭君",
						"id":011,
						"desc":"落雁"
					}, {
						"label": "阴丽华",
						"id":012,
						"desc":"做官当做金吾卫"
					}, {
						"label": "貂蝉",
						"id":013,
						"desc":"闭月"
					}, {
						"label": "大乔",
						"id":014,
						"desc":"铜雀"
					}, {
						"label": "二乔",
						"id":015,
						"desc":"春深"
					},
					{
						"label": "绿珠",
						"id":016,
						"desc":"楼高百尺"
					}, {
						"label": "祝英台",
						"id":017,
						"desc":"蝴蝶飞"
					}, {
						"label": "苏小小",
						"id":018,
						"desc":"可惜"
					}, {
						"label": "张丽华",
						"id":019,
						"desc":"门外韩擒虎"
					}, {
						"label": "蔡文姬",
						"id":020,
						"desc":"穿越三国首推"
					}, {
						"label": "谢道韫",
						"id":021,
						"desc":"丈夫无能"
					}, {
						"label": "甄宓",
						"id":022,
						"desc":"流风回雪"
					}, {
						"label": "李祖娥",
						"id":023,
						"desc":"北齐可怜人"
					}, {
						"label": "武则天",
						"id":024,
						"desc":"千古女帝"
					}, {
						"label": "上官婉儿",
						"id":025,
						"desc":"东施效颦"
					},
					{
						"label": "太平公主",
						"id":026,
						"desc":"不平"
					}, {
						"label": "杨玉环",
						"id":027,
						"desc":"羞花"
					}, {
						"label": "关盼盼",
						"id":028,
						"desc":"可叹"
					}, {
						"label": "李师师",
						"id":029,
						"desc":"君臣同乐"
					}, {
						"label": "杜十娘",
						"id":030,
						"desc":"遇人不淑"
					}, {
						"label": "陈圆圆",
						"id":031,
						"desc":"冲冠一怒"
					}, {
						"label": "董小婉",
						"id":032,
						"desc":"不知道"
					}, {
						"label": "柳如是",
						"id":033,
						"desc":"水太凉"
					}, {
						"label":"李香君",
						"id":034,
						"desc":"书生无用"
					}
				]

				$("#tags").autocomplete({
						minLength: 0,
						source: res,
						focus: function(event, ui) {
							$("#tags").val(ui.item.label);
							return false;
						},
						select: function(event, ui) {
							$("#tags").val(ui.item.label);
							$("#tags-id").val(ui.item.id);
							$("#tags-description").html(ui.item.desc);

							return false;
						}
					})
					.data("ui-autocomplete")._renderItem = function(ul, item) {
						return $("<li>")
							.append("<a>" + item.label+ "-" + item.desc+ "</a>")
							.appendTo(ul);
					};
			});
		</script>
	</head>

	<body>
		<div class="ui-widget">
			<labelfor="tags">标签:</label>
<input id="tags">
<input type="hidden" id="tags-id">
<p id="tags-description"></p>
			
		</div>
	</body>

</html>

第二种,自己写

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-3.3.1.min.js"></script>
		<style>
			
			
			.auto_hidden {
				width: 204px;
				border-top: 1px solid #333;
				border-bottom: 1px solid #333;
				border-left: 1px solid #333;
				border-right: 1px solid #333;
				position: absolute;
				display: none;
			}
			
			.auto_show {
				width: 204px;
				border-top: 1px solid #333;
				border-bottom: 1px solid #333;
				border-left: 1px solid #333;
				border-right: 1px solid #333;
				position: absolute;
				z-index: 9999;
				/* 设置对象的层叠顺序 */
				display: block;
			}
			
			.auto_onmouseover {
				color: #ffffff;
				background-color: highlight;
				width: 100%;
			}
			
			.auto_onmouseout {
				color: #000000;
				width: 100%;
				background-color: #ffffff;
			}
		</style>
		<script>
			var Auto = function(id) {
				return "string" == typeof id ? document.getElementById(id) : id;
			}
			var Bind = function(object, fun) {
				return function() {
					return fun.apply(object, arguments);
				}
			}

			function AutoComplete(obj, autoObj, arr) {
				this.obj = Auto(obj); //输入框
				this.autoObj = Auto(autoObj); //DIV的根节点
				this.value_arr = arr; //不要包含重复值
				this.index = -1; //当前选中的DIV的索引
				this.search_value = ""; //保存当前搜索的字符
			}
			AutoComplete.prototype = {
				//初始化DIV的位置
				init: function() {
					this.autoObj.style.left = this.obj.offsetLeft + "px";
					this.autoObj.style.top = this.obj.offsetTop + this.obj.offsetHeight + "px";
					this.autoObj.style.width = this.obj.offsetWidth - 2 + "px"; //减去边框的长度2px   
				},
				//删除自动完成需要的所有DIV
				deleteDIV: function() {
					while(this.autoObj.hasChildNodes()) {
						this.autoObj.removeChild(this.autoObj.firstChild);
					}
					this.autoObj.className = "auto_hidden";
				},
				//设置值
				setValue: function(_this) {
					return function() {
						_this.obj.value = this.seq;
						_this.autoObj.className = "auto_hidden";
					}
				},
				//模拟鼠标移动至DIV时,DIV高亮
				autoOnmouseover: function(_this, _div_index) {
					return function() {
						_this.index = _div_index;
						var length = _this.autoObj.children.length;
						for(var j = 0; j < length; j++) {
							if(j != _this.index) {
								_this.autoObj.childNodes[j].className = 'auto_onmouseout';
							} else {
								_this.autoObj.childNodes[j].className = 'auto_onmouseover';
							}
						}
					}
				},
				//更改classname
				changeClassname: function(length) {
					for(var i = 0; i < length; i++) {
						if(i != this.index) {
							this.autoObj.childNodes[i].className = 'auto_onmouseout';
						} else {
							this.autoObj.childNodes[i].className = 'auto_onmouseover';
							this.obj.value = this.autoObj.childNodes[i].seq;
						}
					}
				},
				//响应键盘
				pressKey: function(event) {
					var length = this.autoObj.children.length;
					//光标键"↓"
					if(event.keyCode == 40) {
						++this.index;
						if(this.index > length) {
							this.index = 0;
						} else if(this.index == length) {
							this.obj.value = this.search_value;
						}
						this.changeClassname(length);
					}
					//光标键"↑"
					else if(event.keyCode == 38) {
						this.index--;
						if(this.index < -1) {
							this.index = length - 1;
						} else if(this.index == -1) {
							this.obj.value = this.search_value;
						}
						this.changeClassname(length);
					}
					//回车键
					else if(event.keyCode == 13) {
						this.autoObj.className = "auto_hidden";
						this.index = -1;
					} else {
						this.index = -1;
					}
				},
				//程序入口
				start: function(event) {
					if(event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) {
						this.init();
						this.deleteDIV();
						this.search_value = this.obj.value;
						var valueArr = this.value_arr;
						valueArr.sort();
						if(this.obj.value.replace(/(^\s*)|(\s*$)/g, '') == "") {
							return;
						} //值为空,退出
						try {
							var reg = new RegExp("(" + this.obj.value + ")", "i");
						} catch(e) {
							return;
						}
						var div_index = 0; //记录创建的DIV的索引
						for(var i = 0; i < valueArr.length; i++) {
							if(reg.test(valueArr[i])) {
								var div = document.createElement("div");
								div.className = "auto_onmouseout";
								div.seq = valueArr[i];
								div.onclick = this.setValue(this);
								div.onmouseover = this.autoOnmouseover(this, div_index);
								div.innerHTML = valueArr[i].replace(reg, "<strong>$1</strong>"); //搜索到的字符粗体显示
								this.autoObj.appendChild(div);
								this.autoObj.className = "auto_show";
								div_index++;
							}
						}
					}
					this.pressKey(event);
					window.onresize = Bind(this, function() {
						this.init();
					});
				}
			}
			var autoComplete;
			var i = 0;
				var res = ["妹喜", "妲己", "褒姒", "齐姜", "夏姬", "西施", "赵姬", "虞美人", "卓文君", "赵飞燕", "王昭君","阴丽华","貂蝉", "大乔", "二乔", "绿珠", "祝英台", "苏小小", "张丽华", "蔡文姬", "谢道韫", "甄宓", "李祖娥", "武则天", "上官婉儿", "太平公主", "孙窈娘", "杨玉环", "关盼盼", "李师师", "杜十娘", "陈圆圆", "董小婉", "柳如是", "李香君"]
			function search() {
				if(i == 0) {
					autoComplete = new AutoComplete('autoShow', 'autoHide', res);
					i = 1;
				}

				autoComplete.start(event);
			}
			//-->
		</script>
	</head>

	<body>
		<h1 align="center">自动填充</h1>
		<div align="center"><input type="text" style="width:300px;height:20px;font-size:14pt;" id="autoShow" onkeyup="search()"></div>
		<div class="auto_hidden" id="autoHide">
			<!--自动完成 DIV-->
		</div>
		<script>
		</script>
	</body>

</html>
插件使用配置(config)还是很灵活的,当然也是弊端,配置不当,效果就没了。 使用时候,重要的参数如下(此demo参数配置点击右键看源码): url: 'http://suggest.taobao.com/sug?code=utf-8&extras=1', queryName: 'q', //url?queryName=value,默认为输入框的name属性 jsonp: 'callback', //设置此参数名,将开启jsonp跨域功能(我要调淘宝数据,非跨域不可,淘宝的回调参数名就是callback),否则使用json数据结构 item: 'li', //下拉提示项目单位的选择器,默认一个li是一条提示,与processData写法相关。 processData: function(data){ }//自定义处理返回的数据,该方法可以return一个html字符串或jquery对象,将被写入到提示的下拉层中。 右键查看源码,将看到本demo所编写的processData函数是怎样的,所以这个参数是把如何表现交给你来做了,但别忘了配合 item 参数 getCurrItemValue: function($currItem){ }//定义如何去取得当前提示项目的值并返回值,插件根据此函数获取当前提示项目的值,并填入input中,此方法应根据processData参数来定义。 是的,如果你自定义了processData,这个参数恐怕也需要自定义,默认是获取$currItem.html(),你也可以return $currItem.attr('an attrName'); 右键查看源码,将看到本demo所编写的getCurrItemValue函数是怎样的 textchange: function($input){}, //不同于change事件在失去焦点触发,inchange依赖本插件,只要内容有变化,就会触发,并传入input对象 onselect: function($currItem){} //当选择了下拉的当前项目时执行,并传入当前项目。比如选择了某个提示项目,就提交表单。 sequential: 0, //按着方向键不动是否可以持续选择,默认不可以,设置值可以是任何等价的boolean
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值