富文本光标处插入表情

//js

data() {
    return {
      isFocus: false, // 判断输入框是否聚焦
      lastEditRange: null,
      selection: null,
    }
},
methods: {
  ·	// 文本输入框获取焦点事件
    getFocus() {
      this.isFocus = true
      this.$nextTick(() => {
        this.selection = window.getSelection()
        this.lastEditRange = window.getSelection().getRangeAt(0)
      })
    },
    getBlur() {
      this.lastEditRange = window.getSelection().getRangeAt(0)
    },
    // 选择表情
    chatSpace(value, index) {
      if (this.isFocus == true) {
        //当div获取焦点时插入表情
        this.$nextTick(() => {
          if (value.length > 10) {
            let imgDom = document.createElement('img')
            imgDom.src = value
            imgDom.setAttribute('data-id', index + 1)
            if (this.lastEditRange) {
              this.selection.removeAllRanges()
              this.selection.addRange(this.lastEditRange)
            }
            const range = this.selection.getRangeAt(0)
            range.insertNode(imgDom)
            range.collapse(false)
          } else {
            // 普通表情
            let textDom = document.createElement('span')
            textDom.innerHTML = value
            if (this.lastEditRange) {
              this.selection.removeAllRanges()
              this.selection.addRange(this.lastEditRange)
            }
            const range = this.selection.getRangeAt(0)
            range.insertNode(textDom)
            range.collapse(false)
          }
          this.quillEditerRef = document.getElementById('quillEditer')
          // 关闭表情选择器
          let div1 = document.getElementById('expression_select_box')
          div1.style.display = 'none'
        })
      }
    },
}
// html

    
       
{{ face }}
// css省略 // 效果图 ![在这里插入图片描述](https://img-blog.csdnimg.cn/deb6cc6d02e54f13be22f9ffcb897f10.jpeg#pic_center) ![在这里插入图片描述](https://img-blog.csdnimg.cn/6fa43581bbfa413484ec4997211e0b57.jpeg#pic_center) ![在这里插入图片描述](https://img-blog.csdnimg.cn/d9d99f26659c4f69bde52520bb139e20.jpeg#pic_center)

你可能感兴趣的:(富文本)