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】

相关推荐
eokred几秒前
图片预览组件的另一种设计:Headless、可组合、开箱即用
前端·react
南雨北斗6 分钟前
解决web开发中前后端跨域通信(session失效问题)
前端
Y38153266215 分钟前
body-upload-js
前端·javascript·浏览器·深拷贝·数据克隆
Apifox19 分钟前
Apifox 8 月更新|调试、权限与协作体验持续优化
前端·后端·测试
杉氧21 分钟前
React 灵魂:深入剖析 Hooks 与副作用(Side Effects)陷阱
android·前端·react native
Json____24 分钟前
java-宿舍安全卫生检查系统项目源码
java·前端·javascript·课程设计·it学习·wwwoop.com
lichenyang45336 分钟前
鸿蒙ArkUI 键盘避让终极踩坑指南:RESIZE 无效、Column 布局遮挡、折叠屏适配全解
前端
AbelTomato40 分钟前
博客评论系统搭建回顾
javascript·typescript·cloudflare·supabase·hyperdrive
梦醒沉醉42 分钟前
4、函数function
javascript