React中document.getSelection().anchorOffset始终为0?节点类型问题求解
解决React输入框onSelect事件中选中位置始终为0的问题
问题原因
你用document.getSelection()获取输入框的选中偏移量是错误的——这个方法针对的是页面普通文本节点(nodeType=3)的选中状态,而<input>这类表单控件的选中状态是独立维护的。此时document.getSelection()的anchorNode指向的是input元素本身(nodeType=1),所以anchorOffset始终返回0,并非你需要的文本偏移量。
解决方法
直接从事件对象的目标元素(即input控件)上读取原生的selectionStart和selectionEnd属性,这两个属性会直接返回选中文本在输入框内容中的起始、结束索引,完全不需要依赖document.getSelection()。
修改你的代码如下:
<Form.Control id='left' type='text' placeholder='LHS' onSelect={element => logSelection(element)} /> function logSelection(element) { const input = element.target; const fullText = input.value; // 直接用input的原生属性获取选中范围 const selectionStart = input.selectionStart; const selectionEnd = input.selectionEnd; const selectedText = fullText.substring(selectionStart, selectionEnd); // 现在可以正常拿到正确的位置值 console.log('完整文本:', fullText); console.log('选中文本:', selectedText); console.log('选中起始位置:', selectionStart); }
补充说明
selectionStart:选中文本在输入框内容中的起始索引selectionEnd:选中文本在输入框内容中的结束索引- 这两个属性是HTMLInputElement和HTMLTextAreaElement的原生属性,所有现代浏览器都支持,完全适配React的事件场景。
内容的提问来源于stack exchange,提问作者Brownigloo
相关产品推荐
相关产品推荐

