VUE3+TS,div块文字高亮效果

VUE3+TS,实现div块文字可编辑、可高亮关键词

1. div可编辑:contenteditable属性

实现el-input的效果

<div contenteditable="true">{{Text}}</div>

2. div文本高亮方式一:v-html

  • 适合div块内关键词/一部分文字高亮
1. v-html绑定文字

不在是{{}}中写变量的方式

<div  v-html="repairedText"></div>
//script中
let repairedText = ref<string>("")
2. 正则化实现文本高亮
  • v-html绑定的文本才可以加载出来样式,{{Text}}定义的变量直接显示span语句
  • replace实现替换
  • replace可以实现颜色替换、文本替换
repairedText.value = answerText.value.replace(item.original_text, `<span class="highlight-fixed-text">${item.original_text}</span>`)

//style
.highlight-fixed-text{
	color:green;
}

3. div文本高亮方式二::style:class

  • 适合div块的全部文字高亮
设置变量属性highlight ,根据属性值动态切换文本样式

style

<div  v-for="(answerItem, answerIndex) in answerClaims" :key="answerIndex"  
		@click="highlightClaim(answerItem)" :class="answerItem.highlight ? 'highlighted-text' : ''">

script:动态修改highlight 的取值

 answerClaims.value.forEach((item) => {
    if (item.data === element.data) {
      item.highlight = true
    } else {
      item.highlight = false
    }
  })

style

.highlighted-text {
  background-color: rgba(64, 158, 255, 0.3);
  border-radius: 3px;
}

Tips

  1. computed:个人觉得,调接口获取的值推荐使用watch,但是对接口结果进一步加工显示的数据,最好用computed,它的优点就是一旦某个值发生变化后,页面会自动重新计算、重新渲染,不需要watch一直监听
  2. repalce:在样式动态修改上很有用!
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3 + TypeScript + Vite 中,可以使用 `:class` 指令来动态绑定 `class` 属性。 下面是一个示例代码: ```vue <template> <div :class="{'red': isRed, 'blue': isBlue}"> <h1>动态修改 class</h1> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ setup() { const isRed = ref<boolean>(true); const isBlue = ref<boolean>(false); const toggleClass = () => { isRed.value = !isRed.value; isBlue.value = !isBlue.value; }; return { isRed, isBlue, toggleClass, }; }, }); </script> <style> .red { background-color: red; } .blue { background-color: blue; } </style> ``` 在这个示例中,我们使用 `:class` 指令绑定了一个对象,对象的属性名是 `class` 名称,属性值是一个布尔值,表示该 `class` 是否应用于元素。当 `isRed` 值为 `true` 时,`red` 类将添加到元素上;当 `isBlue` 值为 `true` 时,`blue` 类将添加到元素上。 在 `setup` 函数中,我们定义了 `isRed` 和 `isBlue` 两个变量,并初始化为 `true` 和 `false`。然后,我们定义了一个 `toggleClass` 函数,用来切换 `isRed` 和 `isBlue` 的值,从而动态修改元素的 `class`。 最后,我们在模板中使用了 `:class` 指令,并绑定了 `isRed` 和 `isBlue` 变量。当 `toggleClass` 函数被调用时,`isRed` 和 `isBlue` 的值将发生改变,从而动态修改元素的 `class`。 需要注意的是,为了使用 `:class` 指令,需要在模板中使用 `v-bind` 或 `:` 前缀。在对象中,属性名必须是字符串,属性值可以是布尔值、字符串、数组或对象。在本例中,我们使用了布尔值来动态添加或移除 `class`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值