JavaScript實(shí)現(xiàn)搜索聯(lián)想關(guān)鍵字高亮功能
使用原生js+css+html實(shí)現(xiàn)的輸入框搜索聯(lián)想的功能,并集搜索關(guān)鍵字高亮。

完整代碼如下:
不需要任何依賴庫,粘貼復(fù)制即可運(yùn)行。
<!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>搜索關(guān)鍵字高亮</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="請輸入搜索關(guān)鍵字..." type="text" name="" id="searchResult" value="" />
<button type="button" onclick="onSearch()">搜索</button>
<ul id="associate"></ul>
</div>
<script>
/**
* 解決動態(tài)生成元素?zé)o法綁定事件
* @param {Object} type 事件類型
* @param {Object} fun 回調(diào)函數(shù)
*/
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("選項(xiàng)被點(diǎn)擊:", this.childNodes);
document.getElementById("searchResult").value = globalSearchKey.trim();
globalSearchKey = '';
console.log("globalSearchKey",globalSearchKey)
// associate.style.display = 'none';
associate.style.visibility = 'hidden';
});
}
}
/**
*思路:把包含搜索關(guān)鍵字的位置分四種情況考慮:
* 1.沒有找到匹配到搜索關(guān)鍵字,直接返回原字符串
* 2.搜索關(guān)鍵字在頭部
* 3.搜索關(guān)鍵字在尾部
* 4.搜索關(guān)鍵字在中間
* 搜索關(guān)鍵字高亮
* @param {Object} source 原字符串[搜索結(jié)果]
* @param {Object} target 子字符串[搜索關(guān)鍵字]
*/
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/>`;
}
}
}
// 聯(lián)想數(shù)據(jù)
let shading = [
'java入門到入土',
'30天精通java',
'java編程思想',
'jvm虛擬機(jī)參數(shù)調(diào)優(yōu)',
'為什么jdk更新那么快?',
];
function onSearch() {
let currentSearchKey = document.getElementById("searchResult").value;
if (!currentSearchKey) {
alert("搜索關(guān)鍵字不能為空!")
}
alert("當(dāng)前搜索關(guān)鍵字:" + currentSearchKey);
// associate.style.display = 'none';
associate.style.visibility = 'hidden';
}
let dom = document.getElementById("searchResult");
// 輸入框值改變匹配關(guān)鍵字高亮[底紋數(shù)據(jù)可換成聯(lián)想數(shù)據(jù)]
dom.oninput = (event) => {
if (!event.target.value) {
associate.innerHTML = '<li>暫無匹配數(shù)據(jù)!</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');
}
// 輸入獲得焦點(diǎn)[獲取底紋數(shù)據(jù)]
dom.onfocus = (event) => {
hint();
}
// 輸入失去焦點(diǎn)
dom.onblur = (event) => {
console.log("失去焦點(diǎn)")
}
/**
* 獲得焦點(diǎn)是提示的底紋
*/
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實(shí)現(xiàn)搜索聯(lián)想關(guān)鍵字高亮功能的詳細(xì)內(nèi)容,更多關(guān)于JavaScript關(guān)鍵字高亮的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript函數(shù)式編程(Functional Programming)高階函數(shù)(Higher order fun
這篇文章主要介紹了JavaScript函數(shù)式編程(Functional Programming)高階函數(shù)(Higher order functions),結(jié)合實(shí)例形式分析了javascript函數(shù)式編程高級函數(shù)的概念、原理、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-05-05
JavaScript在網(wǎng)頁中畫圓的函數(shù)arc使用方法
這篇文章主要介紹了JavaScript在網(wǎng)頁中畫圓的函數(shù)arc使用方法的相關(guān)資料,需要的朋友可以參考下2015-11-11
Navigator?sendBeacon頁面關(guān)閉也能發(fā)送請求方法示例
這篇文章主要為大家介紹了Navigator?sendBeacon頁面關(guān)閉也能發(fā)送請求的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
uni-app基本的數(shù)據(jù)綁定v-bind,v-for,v-on:click詳解
這篇文章主要介紹了uni-app基本的數(shù)據(jù)綁定v-bind,v-for,v-on:click,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08

