需求:
一段文本,选中的文本去和要求文本匹配,并且标注颜色。
鼠标选中
Window getSelection() 方法 | 菜鸟教程
window.getSelection() 方法获取鼠标划取部分的起始位置和结束位置的问题
window.getSelection().anchorOffset; //开始位置
window.getSelection().focusOffset; //结束位置
Window getSelection() 确认用户选择的文本范围或光标的当前位置。
// 选中的文本和起始位置
regexp() {
let locationArr={}
let regtext = window.getSelection().toString();
if (regtext) {
// 下标需要从0开始
locationArr[0] = window.getSelection().anchorOffset - 1;
locationArr[1] = window.getSelection().focusOffset - 1;
}
},
// v-html 特殊字符显示
fn(data){
const text = data.replace(/</g, '<').replace(/>/g, '>');
const color = this.returnRgba();// 自定义颜色
//匹配传入的搜索值不区分大小写 i表示不区分大小写,g表示全局搜索 匹配标签
let rReg = new RegExp(`${str}`, "");
//替换后的值
if (!(val === '')) {
const color = this.returnRgba();
// 日志样本
this.fileLineTemplateShow[index] =
`<span style="background:${color}">` + this.fileLineTemplate[0].slice(e[1][0], e[1][1]) + '</span>'
// 正则表达式
`<span style="background:${color}">` + text + '</span>';
} else {
this.snmpForm.un_reg += text;
}
// rgb颜色随机
returnRgba() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgba(${r},${g},${b}, 0.2)`;
},
```\
[也可以参考这个博主](https://blog.csdn.net/weixin_44058725/article/details/126507818)