highlight.js 实现搜索关键词高亮效果

发布时间:2024年01月12日

先看效果:
在这里插入图片描述
折腾了老半天,记录一下
注意事项都写注释了
代码:

<template>
  <div class="absolute-lt wh-full overflow-hidden p-10">
   
    <div style="width: 200px">
      <el-input v-model="keyword" @input="search"></el-input>
    </div>
    <code>
      <pre v-html="html"></pre>
    </code>
  </div>
</template>
<script setup>
import { onMounted, computed, reactive, ref } from "vue";
import hljs from "highlight.js";
// 这不引入样式防止干扰高亮显示
// import "highlight.js/styles/arta.css";
const str = `
Server: cloudflare
Date: Tue, 02 Jan 2024 15:40:15 GMT
Content-Type: text/html
Content-Length:  553
Connection: keep
CF-RAY: 83f419748811fa1a-SJC

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>cloudflare</center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->

`;
const html = ref("");
const keyword = ref("");
let saveValue = ref("");

// 注册自定义语言,防止生成多余标签匹配
hljs.registerLanguage("custom", function () {
  return {};
});
html.value = saveValue.value = hljs.highlight(str, { language: "custom" }).value;


function search() {
  if (!keyword.value) return (html.value = saveValue.value);
  let reg = new RegExp(keyword.value, "g", "i");
  html.value = saveValue.value.replace(
    reg,
    "<span class='abc'> " + keyword.value + " </span>"
  );
}
</script>

<style lang="less">
span.abc {
  color: red;
}
</style>

文章来源:https://blog.csdn.net/weixin_42630688/article/details/135541355
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。