富文本插入字段

1,174 阅读1分钟

记录一段业务场景下的代码

业务场景:编辑群发短信模板,模板中在指定位置插入字段。insertWord方法入参btn就是插入的字段。

想记录的主要是重新计算光标位置并重新赋光标在富文本

insertWord(btn) {
  // 获取textarea标签
  const field = document.getElementsByName('tempalteContent')[0]
  // textarea光标开始位置
  const startPos = field.selectionStart
  // textarea光标结束位置
  const endPos = field.selectionEnd
  // textarea多行位置
  // const restoreTop = field.scrollTop
  // 获取之前textarea中的内容
  const value = this.ruleForm.content
  // 光标插入位置前的内容
  const startContent = value.substring(0, startPos)
  // 光标插入位置后的内容
  const endContent = value.substring(endPos, value.length)
  // 将插入后完整的内容重新赋值给texrarea
  this.ruleForm.content = `${startContent}{${btn.value}}${endContent}`
  // 光标应该停留的位置
  const location = startPos + btn.value.length + 2
  this.$nextTick(() => {
    field.focus()
    // 添加光标
    field.setSelectionRange(location,location)
  })
},