在日常项目中我们往往会有搜索高亮的需求,下面方法可帮助我们实现,可能不是最优但是可以解决
代码实现
<template>
<div>
<el-input v-model="searchText" placeholder="Type a word to highlight" @input="changeinput"/>
<div v-html="dataval"></div>
</div>
</template>
<script setup lang="ts">
import { ref ,watchEffect} from 'vue'
const searchText = ref('')
const data = ref('在上面的例子中,我们将输入框中输入的值绑定到 searchText 变量上,然后将 searchText 和样例文本 sampleText 传递给 WordHighlighter 组件即可。当用户在输入框中输入文本时,WordHighlighter 组件会自动更新高亮的文本内容。注意:WordHighlighter 组件默认只会高亮第一个匹配项,如果需要高亮所有匹配项,可以设置 global 属性为 true。完整的示例代码如下:')
const dataval = ref('')
const changeinput = (val:any) => {
if (val) {
const reg = new RegExp(val, 'ig') //正则匹配
dataval.value = data.value.replace(reg, (match)=> { //替换对应字符
return `<span style="color:red">${match}</span>`
})
} else {
dataval.value = data.value
}
}
//监听使dataval 等于data
watchEffect(() => {
dataval.value = data.value
})
</script>
<style lang="scss" scoped>
</style>
效果
原生js实现
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<input type="text" id="searchInput" placeholder="Search">
<p id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac metus
ac risus lacinia malesuada. Curabitur eget mi euismod, tincidunt lacus
nec, sodales lectus. Sed vitae mi at sem tristique varius. Nulla facilisi.
Phasellus sed justo magna. Sed ullamcorper enim vitae lectus vehicula,
sit amet mollis libero lacinia. Vestibulum ante ipsum primis in faucibus
orci luctus et ultrices posuere cubilia Curae; Sed auctor, urna a facilisis
tristique, lacus sem lacinia ex, et efficitur mi eros sit amet metus.
</p>
<script>
function highlightText(searchTerm) {
const contentElement = document.getElementById('content');
const content = contentElement.textContent;
const regex = new RegExp(searchTerm, 'gi');
const highlightedContent = content.replace(regex, match => `<span class="highlight">${match}</span>`);
contentElement.innerHTML = highlightedContent;
}
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', function () {
console.log(this.value.trim());
const searchTerm = this.value.trim();
highlightText(searchTerm);
});
</script>
</body>
</html>