1.低配版(不带特殊字符转义,不区分大小写):
获取要高亮匹配的盒子,再实现盒子里的innerHTML高亮匹配
let r = document.getElementsByClassName('ivu-tree-title')
let nodeList = Array.from(r)
if (nodeList.length) {
nodeList.forEach(item => {
item.innerHTML = item.innerHTML.replaceAll(searchKey, `<span style="color: #436BF6">${searchKey}</span>`)
})
}2. 高配版(带特殊字符转义,带大小写匹配):
①v-html绑定处理高亮的函数
②实现高亮
markHighLight (str, keyword) {
// 正则表达式的第二个参数,忽略带小写和全局
return str.replace(new RegExp(format(keyword), 'ig'), str => setHighLight(str))
function setHighLight (str) {
return `<em style="color: #E34B4B;font-style: normal;">${str}</em>`
}
function format(str) {
const sp = '[`~!@#$%^&*()_+<>?:"{},.\/;\'[\]'.split('')
const arr = str.split('')
const res = []
arr.forEach((item) => {
if(sp.indexOf(item) !== -1) {
item = '\\' + item
}
res.push(item)
});
return res.join('')
}
}版权声明:本文为qq_42039912原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。