1.将div设置contenteditable属性变成富文本
<div contenteditable
ref="textInput"
id="drop-area"
rows="4"
resize="false"
class="textInput h100 overflow-x"
@focus="focus = true"
@blur="focus = false"
@input="inputChange"
@keydown.enter.exact.prevent="handleEnter"
@keyup.ctrl.enter.prevent.exact="handleLine"
@keydown.up.stop="handleUp"
@keydown.down.stop="handleDown">
</div>
2.生命周期 mounted绑定粘贴事件
this.$refs['textInput'].addEventListener('paste', this.handlePaste)
3.粘贴函数
/**
* 粘贴图片
*/
handlePaste(){
const clipboardData = e?.clipboardData
const file = clipboardData?.files[0]
/**
* 获取图片按比例缩小的宽度
*/
getImgWidth(file).then((width) => {
const src = fileToUrl(file)
const uid = this.getUid()
document.execCommand('insertHTML', false, `<img src="${src}" ondblclick="handelImage(\'' + src + '\')" width=${width} uid=${uid} />`)
// 存储复制的文件流
this.copyImgList.push({ file, uid })
})
}
富文本聚焦:
/**
* 输入框聚焦
*/
getSelectPos() {
var esrc = this.$refs['text-input']
var range = document.createRange()
range.selectNodeContents(esrc)
range.collapse(false)
var sel = window.getSelection()
sel.removeAllRanges()
sel.addRange(range)
},