前端实现高亮文字的方式

120 阅读1分钟
1. 场景: 高亮部分内容,突出展示

在处理页面展示时,因为内容过多不便查看,需要根据一些关键词高亮部分内容,进行突出处理。

image.png

实现:利用插入标签的方式对正则匹配到的结果进行背景颜色处理,达到内容高亮效果。

data() {
    return {
        // 需要高亮的内容
        highlight: ['春和景明', '岸芷汀兰', '浮光跃金,静影沉璧'],
        initLog: '至若春和景明,波澜不惊,上下天光,一碧万顷,沙鸥翔集,锦鳞游泳,岸芷汀兰,郁郁青青。而或长烟一空,皓月千里,浮光跃金,静影沉璧,渔歌互答,此乐何极!登斯楼也,则有心旷神怡,宠辱偕忘,把酒临风,其喜洋洋者矣。',
        showLog: ''
    };
},

methods: {
    turnFormatList() {
      this.showLog = JSON.parse(JSON.stringify(this.initLog));
      this.highlight.map(item => {
        // 转义字符串中特殊字符
        const text = item.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        // 创建一个正则
        const regExp = new RegExp(text, 'g');
        const color = this.returnRgba();
        
        // 匹配内容通过 span 标签添加背景色 实现高亮效果
        this.showLog = this.showLog.replace(regExp, `<span style="background: ${color};">${item}</span>`);
        // 数组格式
        // this.showLog = this.showLog.map(e => {
        //   return e.replace(regExp, `<span style="background: ${color};">${e}</span>`)
        // });
      });
    },

    // 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.3)`;
    }
  }

用 v-html 渲染处理过的内容

 <!-- 字符串 -->
<div v-html="showLog"></div>

 <!-- 数组 -->
<div v-for="(item, i) in showLog" :key="i">
    <div v-html="item"></div>
</div>
2. 参考地址

juejin.cn/post/706643…