react如何获取光标
获取光标位置的方法
在React中获取光标位置通常涉及处理输入框或可编辑元素的选区(Selection)和范围(Range)。以下是几种常见场景的实现方式:
监听输入框的光标位置
通过onSelect或onClick事件结合selectionStart和selectionEnd属性获取光标位置:
function TextInput() {
const handleSelection = (e) => {
const cursorPosition = e.target.selectionStart;
console.log('Cursor position:', cursorPosition);
};
return (
<input
type="text"
onSelect={handleSelection}
onClick={handleSelection}
/>
);
}
获取可编辑元素的光标位置
对于contentEditable的div,需通过window.getSelection()API:
function EditableDiv() {
const handleKeyUp = () => {
const selection = window.getSelection();
const cursorPosition = selection.getRangeAt(0).startOffset;
console.log('Cursor position:', cursorPosition);
};
return (
<div
contentEditable
onKeyUp={handleKeyUp}
onClick={handleKeyUp}
/>
);
}
动态设置光标位置
通过setSelectionRange控制输入框的光标:
function SetCursorPosition() {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.setSelectionRange(5, 5); // 将光标定位到第5个字符
}
}, []);
return <input ref={inputRef} type="text" />;
}
处理多行文本的光标
对于textarea,需考虑换行符的影响。通过selectionStart获取的行列位置:

function TextAreaCursor() {
const handleCursor = (e) => {
const text = e.target.value;
const pos = e.target.selectionStart;
const lines = text.substr(0, pos).split('\n');
const row = lines.length;
const col = lines[lines.length - 1].length;
console.log(`Row: ${row}, Column: ${col}`);
};
return <textarea onSelect={handleCursor} onClick={handleCursor} />;
}
兼容性注意事项
- 现代浏览器均支持
selectionStart/End和getSelection()。 - 对于复杂富文本编辑,建议使用专门的库如
Slate.js或Draft.js,它们封装了更完善的选区管理。 - 移动端可能需要额外处理触摸事件触发的选区变化。






