在标签上添加@mouseup事件
<div v-html="text" @mouseup="handleMouseSelect"></div>
选取文字高亮方法
handleMouseSelect () {
// window.getSelection().toString()获取鼠标选定的文字
var text = window.getSelection().toString()
// 避免未选择文字时对字符串进行替换
if (text !== '') {
// 颜色、背景可以自行更改
const replaceString = `<span class="tagX" style="color: ${this.colors[keywordIndex].color}; background: ${this.colors[keywordIndex].background}">${text}</span>`
var temp = []
var reg = new RegExp(text, 'g')
temp = (this.text.replace(reg, replaceString))
this.text = temp
}
效果图:

点击取消高亮——鼠标悬停样式
.tagX:hover {
color: #000 !important;
cursor: poin

这篇博客详细介绍了在Vue项目中如何实现在标签上添加@mouseup事件以实现文字选取高亮,并提供了点击取消高亮的方法,包括鼠标悬停时的样式处理和功能实现。通过文中提供的步骤和示例,读者可以掌握这一实用功能的实现技巧。
最低0.47元/天 解锁文章
1198





