js控制input光标位置
时间: 2023-07-20 15:43:16 浏览: 50
可以使用 JavaScript 的 Selection API 来控制 input 光标位置。具体方法如下:
```javascript
// 获取 input 元素
const input = document.getElementById('input');
// 设置光标位置
function setCursorPosition(pos) {
const range = document.createRange();
const selection = window.getSelection();
range.setStart(input, pos);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
// 获取光标位置
function getCursorPosition() {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(input);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
return preSelectionRange.toString().length;
}
// 示例
input.addEventListener('click', () => {
// 设置光标位置到末尾
setCursorPosition(input.value.length);
});
```
以上代码实现了点击 input 元素时将光标位置设置到末尾。你可以根据需要调整代码实现你想要的功能。