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】

相关推荐
正小安1 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光3 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   3 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   3 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web3 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常3 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇4 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr4 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho5 小时前
【TypeScript】知识点梳理(三)
前端·typescript