js 利用window.getSelection() 实现简单的文字标注(鼠标选中文本,给其加、背景色等等)

需求
一段文本,选中的文本去和要求文本匹配,并且标注颜色。
在这里插入图片描述

鼠标选中
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, '&lt').replace(/>/g, '&gt');
			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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值