html:
// contenteditable: 可编辑属性,true or false
// ref: 定位dom
<div contenteditable="true" class="card-content" ref="cardAreaRef" placeholder="请输入或在右侧选择"></div>
js:
选中右侧或底部
// link:想添加的标签,啥都行
// (this.$refs.cardAreaRef as any).focus(): 定位光标位置
checkColumn (item: any) {
// this.contentForm.dynamicTags.push(item)
const ele = (this.$refs.cardAreaRef as any)
const link = `<el-link :underline="false" type="primary" contenteditable="false" class="link_edit" data-id="${item.id}">
#${item.name}</el-link>`;
(this.$refs.cardAreaRef as any).focus()
// document.getElementById('sdsds').focus()
this.insertLinkArea(link) // 光标插入
this.formatterSmsContent(ele) // 遍历处理div的数据
}
添加到焦点位置
/**
* name: 添加到焦点位置
* params: html(要插入的标签,此处是el-link)
* method: click
*/
insertLinkArea (html: any) {
let sel: any
let range: any
if (window.getSelection) {
sel = window.getSelection()
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0)
range.deleteContents()
const el = document.createElement('div')
el.innerHTML = html
const frag = document.createDocumentFragment()
let node; let lastNode
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node)
}
range.insertNode(frag)
if (lastNode) {
range = range.cloneRange()
// range.setStartAfter(lastNode)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}
}
}
}
选中右侧字段之后做的处理
/**
* name: 选中右侧字段之后做的处理
* params: value(可编辑div的dom)
* params:value.childNodes (遍历dom的子节点,包括插入的和手写的)
*/
formatterSmsContent (value: any) {
const list: any[] = []
let result: any = ''
value.childNodes.forEach((k: any) => {
switch (k.nodeName) {
case '#text': {
// 处理刚开始输入内容时k.data显示29个空白的问题
const reg = /^[\s]{29}$/g
if (!reg.test(k.data)) {
str += k.textContent
strLength += Number(k.textContent.length
break
}
case 'EL-LINK': {
str += k.attributes['data-title'].value
strLength += Number(k.attributes['data-count'].value)
break
}
default: {
str += k.textContent
strLength += Number(k.textContent.length)
// 为了解决粘贴复制带标签到输入框
value.innerHTML = value.innerText
}
}
})
}