vue使用contenteditable 实现光标处插入自定义图片
前几天接到一个需求,要自定义编辑短信模板但是里面有 姓名,日期这样的标签,为了用起来方便于是决定让用户自己选中插入,类似富文本插入图片那样,好了废话不多说,展示。
<template>
<div class="content-padding">
<div class="shortMessage-tag">
<!-- 插入图片的标签 -->
<img @click="handleTag" :src="require('../../../static/images/name.png')">
</div>
<div
@click="handleSelection"
@input="handleSelection"
class="shortMessage-div_input"
contenteditable="true">
<div>请输入</div>
</div>
</div>
</template>
<script>
import '../../assets/styles/vip/module/welfare.scss'
export default {
data() {
return {
selection: null,
range: null,
textNode: null,
rangeStartOffset: null
}
},
methods: {
// 点击要插入的图片
handleTag(e) {
const parseDom = this.parseDom(
`<img @click="handleTag" src="${require('../../../static/images/name.png')}">`
)
// 在光标处插入dom
this.range.insertNode(parseDom)
// 光标开始和光标结束重叠
this.range.collapse(true)
},
// 记录光标位置等 (debounce防抖提升性能)
handleSelection() {
this.selection = getSelection()
// 光标对象
this.range = this.selection.getRangeAt(0)
// 获取光标对象的范围界定对象
this.textNode = this.range.startContainer
// 获取光标位置
this.rangeStartOffset = this.range.startOffset;},
// 转dom对象
parseDom(arg) {
var objE = document.createElement("div");
objE.innerHTML = arg;
return objE.childNodes[0];
}
}
}
</script>