我有一个 contenteditable div,像这样:
<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>
为此我使用以下代码:
<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>
当我在 div 中四处移动插入符号时单击按钮,返回插入符号在 div 中的实际位置(偏移量)。
问题是,当我将 contenteditable div 替换为输入类型 = 文本或密码控件,并保持 contenteditable 属性 = true,然后单击按钮时,我总是得到零。这是为什么?
感谢您的关注。
最佳答案
在大多数浏览器中,window.getSelection()
仅适用于文本节点内的选择和文档内的元素。它不适用于 <input>
内的文本和 <textarea>
元素(尽管在 WebKit 中 window.getSelection().toString()
将在聚焦文本输入或文本区域内返回选定的文本。参见 http://jsfiddle.net/PUdaS/ )。要在输入中获取选择,请使用输入的 selectionStart
and selectionEnd
属性:
<input type="text" id="test" value="Some text">
<input type="button" value="Click me"
onclick="alert(document.getElementById('test').selectionEnd);">
请注意,IE 8 及更高版本不支持 selectionStart
和 selectionEnd
属性,和一个 different, more complicated solution是必须的。 IE 不支持 window.getSelection()
要么,因此此代码将适用于您的原始代码所支持的所有浏览器。
关于javascript - 如何让 window.getselection 为输入类型=文本字段工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5072155/