← 中文资源

简体中文版本

setSelectionRange 移动输入框光标

程序化写入 value 后光标常停在开头:用 setSelectionRange 把光标移到末尾或预选中一段,selectionStart、selectionEnd、selectionDirection 可随时回读当前选区状态。

阅读英文原文

实现说明

field 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 直接运行文件,输出会带上标签,比如 caret at:、selected:、direction:——输出的每一行都能指回产生它的那次调用。

常见问题

「setSelectionRange 移动输入框光标」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

field.setSelectionRange(field.value.length, field.value.length);
const field = document.querySelector('#token');
field.setSelectionRange(3, 8, 'backward');

代码示例

// Programmatic value writes leave the caret at the start; form code
// uses setSelectionRange to place it deliberately
const field = document.querySelector('#token');
field.value = 'sk_live_9f3ab77c01';

// Caret to the end, where the next keystroke should land
field.focus();
field.setSelectionRange(field.value.length, field.value.length);
console.log('caret at:', field.selectionStart, field.selectionEnd);

// Preselect the prefix so the next input replaces it in one step
field.setSelectionRange(0, 7);
console.log('selected:', field.selectionStart, field.selectionEnd);

// The optional direction decides how Shift+Arrow extends this selection
field.setSelectionRange(3, 8, 'backward');
console.log('direction:', field.selectionDirection);