JavaScript实现搜索联想关键字高亮功能

使用原生js+css+html实现的输入框搜索联想的功能,并集搜索关键字高亮。

完整代码如下:

不需要任何依赖库,粘贴复制即可运行。

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>搜索关键字高亮</title>
	</head>
	<style type="text/css">
		.fonthighlight {
			color: red;
			font-weight: 600;
			font-size: 16px;
		}

		input {
			height: 25px;
			width: 300px;
			padding: 0;
			margin: 0;
		}

		button {
			padding: 0;
			margin: 0;
			height: 30px;
			width: 80px;
			background-color: orange;
			border: none;
		}

		button:hover {
			color: red;
			background-color: #00aaff;
		}

		ul {
			padding-left: 5px;
			margin-top: 5px;
			width: 300px;
			background-color: #efefef;
			border: #F0F0F0 solid 2px;
			border-radius: 0.2rem;
			display: none;
		}

		ul li {
			list-style-type: none;
			text-align: left;
			padding: 0;
			margin-top: 5px;

		}

		ul li:hover {
			background-color: #c7c7c7;
			cursor: pointer
		}
	</style>
	<body>

		<div>
			<input placeholder="请输入搜索关键字..." type="text" name="" id="searchResult" value="" />
			<button type="button" onclick="onSearch()">搜索</button>
			<ul id="associate"></ul>
		</div>
		<script>
			/**
			 * 解决动态生成元素无法绑定事件
			 * @param {Object} type 事件类型
			 * @param {Object} fun 回调函数
			 */
			Element.prototype.on = function(type, fun) {
				window.addEventListener ? this.addEventListener(type, fun) : this.attachEvent('on' + type, fun);
			}

			let globalSearchKey = ''

			let associate = document.querySelectorAll("#associate")[0];

			function bindEvent(associateChildNodes, event) {
				for (let i = 0; i < associateChildNodes.length; i++) {
					associateChildNodes[i].on(event, function() {
						let matchNods = this.childNodes;
						if (matchNods && matchNods.length > 0) {
							for (let i = 0; i < matchNods.length; i++) {
								globalSearchKey += matchNods[i].innerHTML;
							}
						}

						console.log("选项被点击:", this.childNodes);
						document.getElementById("searchResult").value = globalSearchKey.trim();
						globalSearchKey = '';
						console.log("globalSearchKey",globalSearchKey)
						// associate.style.display = 'none';
						associate.style.visibility = 'hidden';
					});
				}
			}



			/**
			 *思路:把包含搜索关键字的位置分四种情况考虑:
			 * 1.没有找到匹配到搜索关键字,直接返回原字符串
			 * 2.搜索关键字在头部
			 * 3.搜索关键字在尾部
			 * 4.搜索关键字在中间
			 * 搜索关键字高亮
			 * @param {Object} source 原字符串[搜索结果]
			 * @param {Object} target 子字符串[搜索关键字]
			 */
			function highlightText(source, target) {
				if (!source || !target) {
					return '';
				} else {
					let indexPosition = source.indexOf(target)
					if (indexPosition != -1) {
						let sourceLength = source.length;
						let prefix = source.substring(0, indexPosition);
						let suffixIndex = (prefix ? prefix.length : 0) + (target ? target.length : 0);
						let suffix = source.substring(suffixIndex, sourceLength);
						if (indexPosition == 0) {
							return `<span class="fonthighlight target">${target}</span><span class="suffix">${suffix}</span>`;
						} else if (indexPosition + target.length == source.length) {
							return `<span class="prefix">${prefix}</span><span class="fonthighlight target">${target}</span>`;
						} else {
							return `<span>${prefix}</span><span class="fonthighlight target">${target}</span><span>${suffix}</span>`;
						}
					} else {
						return `<span>${source}<span/>`;
					}
				}
			}

			// 联想数据
			let shading = [
				'java入门到入土',
				'30天精通java',
				'java编程思想',
				'jvm虚拟机参数调优',
				'为什么jdk更新那么快?',
			];


			function onSearch() {
				let currentSearchKey = document.getElementById("searchResult").value;
				if (!currentSearchKey) {
					alert("搜索关键字不能为空!")
				}
				alert("当前搜索关键字:" + currentSearchKey);

				// associate.style.display = 'none';
				associate.style.visibility = 'hidden';
			}

			let dom = document.getElementById("searchResult");
			// 输入框值改变匹配关键字高亮[底纹数据可换成联想数据]
			dom.oninput = (event) => {
				if (!event.target.value) {
					associate.innerHTML = '<li>暂无匹配数据!</li>';
					return;
				}
				let matchHtml = '';
				shading.forEach((item, index, slef) => {
					let matchResultText = highlightText(item, event.target.value);
					matchHtml += (`<li>` + matchResultText + "</li>");
				});

				associate.innerHTML = matchHtml;
				// 重新渲染一定要重新绑定事件
				let associateChildNodes = associate.childNodes;
				bindEvent(associateChildNodes, 'click');

			}



			// 输入获得焦点[获取底纹数据]
			dom.onfocus = (event) => {
				hint();
			}
			// 输入失去焦点
			dom.onblur = (event) => {
				console.log("失去焦点")
			}

			/**
			 * 获得焦点是提示的底纹
			 */
			function hint() {
				let associateHtml = '';
				shading.forEach((item, index, slef) => {
					associateHtml += `<li ><span >${item} </span></li>`;
				});

				associate.innerHTML = associateHtml;
				associate.style.display = 'block';

				let associateChildNodes = associate.childNodes;
				associate.style.visibility = 'visible';
				// 绑定事件 
				bindEvent(associateChildNodes, 'click');
			}
		</script>
	</body>

</html>

以上就是JavaScript实现搜索联想关键字高亮功能的详细内容,更多关于JavaScript关键字高亮的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:

  • JavaScript简单实现关键字文本搜索高亮显示功能示例
  • JavaScript实现关键字高亮功能
  • 用JS将搜索的关键字高亮显示实现代码
  • javascript 关键字高亮显示实现代码
  • javascript网页关键字高亮代码
张贴在2