Vue 显示关键词附近内容并高亮显示关键词

使用v-html显示内容,可识别内容里的标签

html 复制代码
<div v-html="surroundingContent(blog.content,input)"></div>
js 复制代码
  methods:{
	//获取内容 的关键词附近的内容
	surroundingContent(content,keyword) {
	  const keywordIndex = content.toLowerCase().indexOf(keyword.toLowerCase());
	  const startIndex = Math.max(0, keywordIndex - 10);
	  const endIndex = Math.min(content.length, keywordIndex + keyword.length + 10);
	  var slicedContent = content.slice(startIndex, endIndex);
	  return this.highlightedContent(slicedContent,keyword);
	},
	//高亮显示关键词
	highlightedContent(content,keyword) {
	  // 使用正则表达式匹配关键词,并用<span>标签包裹高亮显示
	  const highlighted = content.replace(new RegExp(keyword, 'gi'), match => {
		return `<span class="highlight">${match}</span>`;
	  });
	  return highlighted;
	},
	......
}
css 复制代码
<style scoped>
	:deep(.highlight) {
	  color: mediumblue;
	  background-color: yellow; /* 高亮颜色 */
	  font-weight: bold;
	}
	...
</style>

解决vue中使用v-html接收后端返回的数据时css样式不能修改的问题

产生问题的原因:由于style里面的scoped,导致v-html里面dom元素的类样式修改不了

解决方案1: 直接在dom的style的行内样式里面写,缺点是一般这个是值是后端直接给你的,行内样式需要拼接,很麻烦。

解决方案2: 在style scoped的下面再写一个style样式,不加scope,专门写这个v-html的样式,需要给v-html里面的dom加一个专门的类,避免全局样式污染到其他页面,因为这个style没有scope。

解决方案3:在style scoped中添加样式穿透:deep(选择器)【推荐使用解决方案3】

相关推荐
前端太佬几秒前
微信小程序支付全流程实战指南(Node.js后端篇)
前端·javascript·微信小程序
_十六几秒前
面试官最爱问的 TypeScript 装饰器:核心原理与实战技巧全解析.md
前端·typescript
代码搬运媛几秒前
mitt 事件发布-订阅库在 react 中的使用
前端
小桥风满袖2 分钟前
Three.js-硬要自学系列17 (拉伸、扫描、多边形轮廓简介、轮廓圆弧、多边形内孔)
前端·css·three.js
Ryan今天学习了吗3 分钟前
从零开始实现命令式组件ElMessage(附代码)
前端
用户2031196600963 分钟前
padding和frame在使用中的顺序问题
前端
资深前端外卖员4 分钟前
【nodejs高可用】Nodejs应用安全防范的问题总结
前端·javascript
袁煦丞4 分钟前
高效文件传输工具FastSend:cpolar内网穿透实验室第567个成功挑战
前端·程序员·远程工作
嘻嘻嘻嘻嘻嘻ys9 分钟前
《Spring Boot 3响应式架构实战:R2DBC驱动的高并发数据持久化革命》
前端·后端