Vue input gets the cursor position and appends content

In the project, it is necessary to add content at any position in the input box. Here, it is realized through the selectionStart attribute of the input and the setSelectionRange method.

First look at the selectionStart attribute, which is used to get the start position of the text box selection area, and selectionEnd is used to get the end position of the text box selection area, for example:

In this function, instead of selecting text, we mainly need to obtain the position of the cursor. When the text is not selected, the values ​​of the selectionStart and selectionEnd properties are the same.

Look at the setSelectionRange method again, it also acts on the input element, you can select a part of a text by setting the start and end positions, inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection), you can also choose the direction. When the start position is the same as the end position, it is equivalent to changing the position of the cursor in the input box.

Take a look at the specific implementation:

code show as below:

async insertContent(val){
   let dom = this.$refs.textareaI.$refs.textarea;
   // console.dir(dom);
   let index  = dom.selectionStart;
   let contont = dom.value;
   this.textarea = contont.substring(0,index) + val + contont.substring(index,contont.length)
   await this.$nextTick();
    dom.focus();
    dom.setSelectionRange(index + val.length,index + val.length)
},

A few points to note: Be sure to wait until the dom update is complete before changing the cursor position;

Another little tip:

Whether it is the element node obtained by ref in vue, or the node obtained by native, when we want to view the properties of the element node, we can view it through these three methods:

  1. package array: console.log([dom])

  1. Package object: console.log({dom})

  1. Use console.dir to print, you can print out all the properties and property values ​​of the object.

Guess you like

Origin blog.csdn.net/m0_49623851/article/details/129182324