美文网首页
contenteditable 实现富文本功能

contenteditable 实现富文本功能

作者: Hsugar | 来源:发表于2020-06-01 19:47 被阅读0次

contenteditable 属性规定是否可编辑元素的内容。

探索来自需求:聊天室的自定义表情换成UI设计图片(╥﹏╥)
讨论了下,发送消息时使用自定义code,图文混排展示url 那么就需要code<->url互转

<div
  id="emoji-editer"
  ref="sendContent"
  class="content"
  contenteditable="true"
  @input="changeText"
  @keydown.enter.prevent="enterInput"
/>
changeText (event) {
  // this.$emit('input', this.$el.innerHTML);
  const emojiStr = event.target.innerHTML
  // let emojiStr = '<img src="http://picspy.lexue.com/come_on_gif.gif">12<img src="http://qiniu.jnwtv.com/LC20180417174434604455636.jpg" style="width: 100px;">设计费';
  let newStr = emojiStr
 // 正则匹配 url 进行替换
  const tempArr = emojiStr.match(/<img(.+?)>/g)
  if (tempArr && tempArr.length > 0) {
    tempArr.map((d, i) => {
      this.list.map(k => {
        if (d.includes(k.pcIconLink)) {
          newStr = newStr.replace(tempArr[i].match(/<img(.+?)>/g), k.iconCode)
        }
      })
    })
  }
  // message为发送的内容
  this.message = newStr
},
 // 获取光标位置及监听输入
enterInput (e) {
  if (e.keyCode === 13 && e.shiftKey) {
    const elInput = document.getElementById('emoji-editer') // 根据id选择器选中对象
    const startPos = elInput.selectionStart// input 第0个字符到选中的字符
    const endPos = elInput.selectionEnd// 选中的字符到最后的字符
    if (startPos === undefined || endPos === undefined) return
    let text = this.message
    text = text.substring(0, startPos) + text.substring(endPos)
    elInput.value = text
    elInput.focus()
    elInput.selectionStart = startPos
    elInput.selectionEnd = startPos
    this.message = text
  } else if (e.keyCode === 13) {
    this.send() // 提交的执行函数
    e.preventDefault()// 禁止回车的默认换行
  }
},
  1. placeholder
    不要写在content里面,用样式empty来设置,否则插入组件之后,删除会自动清空。应该在外层使用div,用绝对定位,移动到你想要的位置
.content:empty::before{
   content: attr(placeholder);
   font-size: 14px;
   color: #CCC;
   line-height: 21px;
   padding-top: 10px;
 }
  1. 清空内容
this.$refs.sendContent.innerHTML = ''

相关文章

网友评论

      本文标题:contenteditable 实现富文本功能

      本文链接:https://www.haomeiwen.com/subject/wajhzhtx.html