前端实现搜索文字变蓝

322 阅读1分钟

背景

我们在开发功能时候,很多时候会涉及到搜索,文本活着下拉的模块,如果配到对应文字,则匹配到的文字变蓝,效果如下,比如微信的效果

微信截图_20240826095355.png

正则匹配对应文字,增加特殊标记,标蓝

原理:replaceAll匹配对应文字,借助vue中的v-html来实现特殊标识

vue3写法及效果如下

<template>
  <div class="w-40">
    <el-input v-model="input" placeholder="请输入内容"></el-input>
    <h3 v-for="item in conList" :key="item.key" v-html="item.label"></h3>
  </div>
</template>
<script lang="ts" setup>
const input = ref();

const conList = computed(() => {
  return list.value.map(item => {
    return {
      ...item,
      label: item.label.includes(input.value) ? item.label.replaceAll(input.value, `<span style="color:red;">${input.value}</span>`) : item.label
    };
  });
});

const list = ref([
  {
    label: "张三丰张",
    key: "1"
  },
  {
    label: "张无忌",
    key: "2"
  },
  {
    label: "白眉鹰王",
    key: "3"
  },
  {
    label: "韦一笑",
    key: "4"
  },
  {
    label: "金毛狮王",
    key: "55"
  }
]);
</script>
<style lang="scss" scoped>
.w-40 {
  width: 40%;
}
</style>


效果如下:

微信截图_20240826111105.png

如果你是纯Html写法,可参考如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>搜索并高亮显示</title>
    <style>
        .highlight {
            color: red;
        }
    </style>
</head>

<body>
    <div id="content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <input type="text" id="search" placeholder="Search text...">

    <script>
        document.getElementById('search').addEventListener('input', function () {
            var searchTerm = this.value.toLowerCase();
            var content = document.getElementById('content');
            if (searchTerm) {
                content.innerHTML = content.textContent.replace(new RegExp(searchTerm, 'gi'), match => `<span class="highlight">${match}</span>`);
            } else {
                content.innerHTML = content.textContent;
            }
        });
    </script>
</body>

</html>

image.png