html
<div ref="editorContent"
id="editorContent"
:class="['editor-content',{'hidden':textLength!=0}]"
contenteditable="true"
@click="watchDivPosition($event)"
@keyup="watchDivPosition($event)"
@input="watchTextLength($event)">
</div>
js
getDivPosition(event) {
const doc = event.target.ownerDocument || event.target.document
const win = doc.defaultView || doc.parentWindow
const range = win.getSelection().getRangeAt(0)
return range
},
setCaretPosition(ctrl, lastEditRange = null) {
if (!lastEditRange) {
window.getSelection().collapse(ctrl, 0)
} else {
const doc = ctrl.ownerDocument || ctrl.document
const win = doc.defaultView || doc.parentWindow
const selection = win.getSelection()
selection.removeAllRanges()
selection.addRange(lastEditRange)
}
},
watchTextLength(event) {
const range = this.getDivPosition(event)
this.lastEditRange = range;
const editorContent = this.$refs.editorContent
if (editorContent.innerHTML == '<br>') {
this.$refs.editorContent.firstChild.remove()
this.updateTextColor(this.textColor[0])
}
const emoDomList = editorContent.querySelectorAll('.emoWH')
const imgDomList = editorContent.querySelectorAll('.imgWH')
this.textLength = editorContent.innerText.length + emoDomList.length + imgDomList.length
if (this.textLength >= 3000) {
this.$Message.warning("文章最长3000字")
}
},
watchDivPosition(event) {
const range = this.getDivPosition(event)
this.lastEditRange = range
let parentNode = range.commonAncestorContainer.parentNode
switch (parentNode.nodeName) {
case 'B':
this.showType = 'textStrong'
this.selectColorValue = '#000000'
break;
case "FONT":
this.selectColorValue = parentNode.color.toUpperCase()
this.showType = ""
break;
case "DIV":
this.showType = undefined
this.selectColorValue = '#000000'
break;
default:
break;
}
if (parentNode.parentNode.nodeName !== 'DIV') {
if (parentNode.parentNode.nodeName == 'B') {
this.showType = 'textStrong'
}
if (parentNode.nodeName == "FONT") {
this.selectColorValue = parentNode.color.toUpperCase()
}
}
},