vue导入 import Highlighter from 'web-highlighter'
实现划选文本高亮代码
1、html代码
<template>
<div style="padding:100px;position:relative;">
<div id="text" style="position:absolute;">
<div>good1230.com-专注于网站排名优化博客建站系统和好文分享</div>
</div>
</div>
</template>
2、js代码
import Highlighter from 'web-highlighter';
const s = {
"startMeta": {
"parentTagName": "DIV",
"parentIndex": 0,
"textOffset": 0
},
"endMeta": {
"parentTagName": "DIV",
"parentIndex": 0,
"textOffset": 12
},
"text": "good1230.com",
"id": "123456"
}
export default {
data () {
return {
highlighter:null,
}
},
mounted: function() {
const opts2 = {
$root: document.querySelector("#text"),
exceptSelectors: ['span','pre', 'code'],
wrapTag: 'a',
style: {
className: 'highlight-mengshou-wrap'
}
}
const highlighter = new Highlighter(opts2);
this.highlighter = highlighter
this.init(highlighter);
},
methods: {
remove(highlighter){
this.highlighter.remove(s.id)
this.highlighter.removeAll()
},
getDoms(id){
let _this = this
const left = this.highlighter.getDoms(id)[0].offsetLeft
const top = this.highlighter.getDoms(id)[0].offsetTop
const o = document.createElement("span");
o.style.left = left - 20 + "px",
o.style.top = top - 25 + "px",
o.dataset.id = id,
o.textContent = "删除",
o.classList.add("my-remove-tip"),
o.onclick = function() {
_this.highlighter.remove(id)
document.querySelector("#text").removeChild(o)
}
o.onmouseover = function() {
_this.highlighter.addClass('highlight-wrap-hover', id);
}
o.onmouseout = function() {
_this.highlighter.removeClass('highlight-wrap-hover', id);
}
document.querySelector("#text").appendChild(o)
},
init(highlighter){
highlighter.run()
highlighter.on('selection:hover', ({id}) => {
highlighter.addClass('highlight-wrap-hover', id);
})
highlighter.on('selection:hover-out', ({id}) => {
highlighter.removeClass('highlight-wrap-hover', id);
})
highlighter.fromStore(s.startMeta, s.endMeta, s.text, s.id);
highlighter.on(Highlighter.event.CREATE, ({sources}) => {
this.getDoms(sources[0].id)
});
this.getDoms(s.id)
},
},
}
css代码
.highlight-mengshou-wrap{background:red!important; color:white}
.highlight-wrap-hover{ background:blue!important; color:white}
.my-remove-tip {
box-sizing: border-box;
position: absolute;
border: 1px solid #fff;
border-radius: 3px;
height: 20px;
width: 40px;
color: #fff;
background: #444;
text-align: center;
font-size: 12px;
cursor: pointer;
line-height: 18px;
overflow: visible;
}
.my-remove-tip::after {
content: '';
position: absolute;
left: 16px;
bottom: -4px;
border-color: #444 transparent transparent;
border-width: 4px 4px 0;
border-style: solid;
height: 0;
width: 0;
}