需求:根据搜索框中的内容,对搜索到的内容结果进行高亮显示
<div class="content" ref="contentSearch" :style="{ height: mainHeight }">
<div class="row" v-if="list.length > 0">
<div class="col" v-for="(item,index) in list" :key="item.id">
<div class="col_title">
<div class="col_title_text" v-html="highlightText(item.topic)"></div>
<div class="col_title_tag" v-for="i in item.rankLevel">{{i || '--'}}</div>
</div>
<div v-if="detailShow" class="col_content" v-html="highlightText(item.content)">
</div>
<div class="col_bto flex-b">
<div class="col_bto_title flex-b">
<div style="color: #666666 ">区域:{{item.name || '--'}}</div>
<div style="color: #666666 ">时间:{{item.deliveryTime || '--'}}</div>
</div>
<div style="color: #0777E5;font-size: 0.7vmax;cursor: pointer" class="flex-c" @click="detail(item)">查看详情<el-icon color=" #0777E5"><DArrowRight /></el-icon></div>
</div>
</div>
</div>
页面利用v-html进行铺设
const highlightText = (text)=> {
// 如果没有关键词或文本为空,直接返回原文
if (!parms.value.keyword || !text) {
return text;
}
// 使用正则表达式进行不区分大小写的全局匹配
const keyword = parms.value.keyword.trim();
const regex = new RegExp(keyword, 'gi');
// 将匹配到的关键词用span标签包裹,并添加高亮样式
return text.replace(regex, match => {
return `<span class="highlight" style="color: red">${match}</span>`;
});
}
js中直接匹配对应文字,进行红色字体显示

被折叠的 条评论
为什么被折叠?



