input 框如何移动光标,设置光标位置?

获取 input 光标位置

const inputDom = document.getElementById("input")
const selectionStart = inputDom.selectionStart

设置 input 光标

inputDom.focus()
// focus() 异步,所以加了 setTimeout
setTimeout(() => {
    
    
  const nextSelection = selectionStart + 1
  inputDom.setSelectionRange(nextSelection, nextSelection)
}, 0)
element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
  • selectionStart: 被选中的第一个字符的位置索引, 从 0 开始。如果这个值比元素的 value 长度还大,则会被看作
    value 最后一个位置的索引。

  • selectionEnd: 被选中的最后一个字符的下一个位置索引。如果这个值比元素的 value 长度还大,则会被看作 value 最后一个位置的索引。

  • selectionDirection:选择方向。forward/backward/none 如果 selectionStart 与
    selectionEnd 相同,不选中任何,光标聚集在 selectionStart/selectionEnd。

     如果 selectionEnd 小于 selectionStart,不选中任何,光标聚集在在 selectionEnd。
    

inputDom.setSelectionRange(0, 4)表现如下图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43631129/article/details/131924817
今日推荐