vue 实现图片粘贴至输入框功能

将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>

生命周期 mounted绑定粘贴事件

           this.$refs['textInput'].addEventListener('paste', this.handlePaste)

         /**
        * 粘贴图片
        */
      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)
    },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容