js how to get and set the position of the cursor in the input box

foreword

When encountering a scene, you need some text labels, click to automatically add them into the text box, then you need to master how to get and set the position of the cursor in the input box, make a record, and record the usage method.

get cursor position

There is an attribute selectionStart on the dom of the input to obtain the starting position of the cursor, and an attribute selectionEnd is the end position.

When the cursor is only selected at a certain position , the two values ​​are the same, and the value is a number. The cursor starts at the left of the first character in the input as 0, and between the first character and the second character is 1, and so on. analogy.

When the cursor selects a certain section of text , these two values ​​get the position of the front and back of the selected text respectively, and the position number is still obtained in the form above.

Two points to note:

  1. SelectionStart and selectionEnd default to 0 until the input is initially unfocused.

  2. If the cursor selects a position or a piece of text, and then loses focus, selectionStart and selectionEnd are still the results of the selection before losing focus .

<body>
<input id="box" value="111"/>
<button onclick="test()">
    获取光标位置
</button>
<script>
    function test() {
        const input = document.getElementById('box')
        console.log(input.selectionStart,input.selectionEnd)
    }
</script>
</body>
复制代码

image.png

image.png

set cursor position

The setSelectionRange function on the input is used to set the cursor position.

Remember to let the input focus before setting the focus. If it is not focused, there will be no cursor.

Two parameters must be passed as input parameters, one starting position and one ending position. If they are set to the same number, the fixed position can be selected . If it is set to two numbers, it is equivalent to selecting the text between the two positions with the mouse .

There is also a third input parameter that can set the direction ("forward" | "backward" | "none"), for example, backward can start counting positions from back to front.

<body>
<input id="box"/>
<button onclick="test()">
    获取光标位置
</button>
<button onclick="test2()">
    设置光标位置为第一个字符与第二个字符之间
</button>
<script>
    function test() {
        const input = document.getElementById('box')
        console.log(input.selectionStart)
    }

    function test2(index) {
        const input = document.getElementById('box')
        input.focus()
        input.setSelectionRange(1, 2)
    }
</script>
</body>
复制代码

insert image description here

end words

If you think the article is helpful to you, please like and collect it. If you have any mistakes or suggestions, you can leave a message, thank you~

Guess you like

Origin juejin.im/post/7086285094528221214