通过自定义指令, 实现搜索关键词高亮。通过自定义指令, 遍历当前元素及其子元素, 如果其内容包含搜索的关键词, 则创建新的dom元素以实现高亮(当前这种方式有一定的弊端, 因为进行dom元素的操作会导致性能下降, 如果有更好的方式, 欢迎留言)。

最终实现效果:

<template>
  <div>
    <div v-keyword-highlight="globalKeyword">
      <h1>关键字高亮</h1>
      <div>关键字高亮</div>
      <div>
        <div>关键字高亮</div>
        <div>
          <p>关键字高亮</p>
          <span>有关键字</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { nextTick } from "vue";
export default {
  data() {
    return {
      globalKeyword: "关键", //搜索关键词
    };
  },
  directives: {
    // 全局搜索关键词高亮
    "keyword-highlight": {
      mounted: function(el, binding) {
        const searchText = binding.value; // 从指令值获取要搜索的文字
        const maxDepth = 10; // 最大递归深度,防止过深的遍历
        // 递归函数,用于遍历DOM树并高亮文本
        function traverseAndHighlight(node, depth) {
          if (depth > maxDepth) {
            return; // 达到最大深度,停止遍历
          }
          if (node.nodeType === Node.TEXT_NODE) {
            const newNodeText = node.nodeValue.replace(
              new RegExp(searchText, "gi"), // 'gi' 标志表示不区分大小写和全局搜索
              (match) => `<span class='global-highlight'>${match}</span>`
            );

            if (newNodeText !== node.nodeValue) {
              // 创建新的文本节点或HTML节点
              const newNode = document.createRange().createContextualFragment(`<span>${newNodeText}</span>`).firstChild;
              node.parentNode.replaceChild(newNode, node);
            }
          } else if (node.nodeType === Node.ELEMENT_NODE && node.childNodes.length && depth < maxDepth) {
            // 递归处理子节点,但限制递归深度
            for (let i = node.childNodes.length - 1; i >= 0; i--) {
              traverseAndHighlight(node.childNodes[i], depth + 1);
            }
          }
        }

        // 在nextTick中执行,确保DOM已经准备好
        nextTick(() => {
          traverseAndHighlight(el, 1); // 从当前元素开始遍历
        });
      },
    },
  },
  created() {},
  mounted() {},
  methods: {},
  beforeUnmount() {},
};
</script>
<style>
.global-highlight {
  color: #2b62e2;
}
</style>

GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐