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

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

<div v-html="surroundingContent(blog.content,input)"></div>
  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;
	},
	......
}
<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. Vue 显示关键词附近内容显示关键词

    2024-07-17 05:14:02       22 阅读
  2. Vue实现SQL语句关键字显示

    2024-07-17 05:14:02       44 阅读
  3. uniapp 搜索内容关键字

    2024-07-17 05:14:02       29 阅读
  4. 对文件内容特殊关键字处理

    2024-07-17 05:14:02       21 阅读
  5. 使用Trie树关键词

    2024-07-17 05:14:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 05:14:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 05:14:02       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 05:14:02       58 阅读
  4. Python语言-面向对象

    2024-07-17 05:14:02       69 阅读

热门阅读

  1. 如何在服务器中安装anaconda

    2024-07-17 05:14:02       28 阅读
  2. ES(笔记)

    2024-07-17 05:14:02       28 阅读
  3. Perl 语言入门学习

    2024-07-17 05:14:02       21 阅读
  4. 使用milvus-sdk-go的迭代器导出数据

    2024-07-17 05:14:02       24 阅读
  5. 通过apache的rewrite实现URL重定向

    2024-07-17 05:14:02       26 阅读
  6. 掌握Conda环境管理:使用conda env remove命令的精要

    2024-07-17 05:14:02       21 阅读
  7. 【python】Request简单使用

    2024-07-17 05:14:02       19 阅读
  8. Redis端口开启防火墙报错

    2024-07-17 05:14:02       23 阅读