关于 textarea 文本域无法回车的问题与解决办法

476 阅读1分钟

前两天遇到一个 bug -- textarea 无法回车的问题。

网上冲浪 + 寻求大佬依然没有找到问题在哪,所以准备用比较笨的方法来处理。

即,获取光标位置。若光标在输入文本最后,则在输入文本最后手动加一个 '/n'。若光标位置在文本中间,则获取光标位置,然后再光标位置出加上一个 '\n'

首先是监听该文本域的回车键,代码如下

    <textarea
      @keydown.enter="enterKey($event)"
      v-model="introduction"
      ref="introduction"
      cols="30"
      rows="10"
      class="textarea"
    />

然后在用户按回车时获取当前光标的位置并根据位置插入 \n,代码如下:

    enterKey(event) {
      let cursorLoca = this.$refs.introduction.selectionStart
      let cursorLoca_ = this.$refs.introduction.selectionEnd
      console.log('cursorLoca >>> ', cursorLoca)
      console.log('cursorLoca_ >>> ', cursorLoca_)
      this.introduction.length === cursorLoca
        ? this.introduction = this.introduction + '\n'
        : this.introduction = this.introduction.slice(0,cursorLoca) + '\n' + this.introduction.slice(cursorLoca)
      this.$nextTick(() => {
        this.$refs.introduction.setSelectionRange(cursorLoca+1, cursorLoca_+1)
      })
    }

上述代码中 DOM.selectionStartDOM.selectionEnd 是获取光标的开始位置与结束位置,DOM.setSelectionRange 是设置光标的位置。

至于为什么要设置光标位置的原因是,如果我们不设置的话,按下回车后光标会直接到内容文本域内容最后的位置,不太匹配用户习惯。加一下会更好一点

以上。