如何让window.getselection为输入类型=文本字段工作 [英] How do I get window.getselection to work for an input type=text field
问题描述
我有一个contenteditable div,像这样:
< div id =testcontentEditable =truestyle =width:600px; height:300px;> Lorem ipsum dolor sit amet< / div>
我使用以下代码:
< input type =buttonvalue =点击我onclick =alert(window.getSelection()。focusOffset.toString());>< / button> ;
当我在div中移动插入符号时单击按钮,返回实际位置( )
问题是,当我用输入type = text或password控件替换contenteditable div时,并保持contenteditable property = true ,并点击按钮,我总是得到一个零。为什么会这样?
感谢您的关注。
浏览器, window.getSelection()
仅适用于文档中文本节点和元素内的选择。它不适用于< input>
和< textarea>
元素中的文本(尽管在WebKit window.getSelection()。toString()
将返回焦点文本输入或textarea中的选定文本。参见 http://jsfiddle.net/PUdaS/ )。要在输入中进行选择,请使用输入的 selectionStart $ c
属性:
$ p $ < code>< code>
< input type =buttonvalue =Click me
onclick =alert(document.getElementById('test')。selectionEnd);>请注意,包含版本8的IE不支持
selectionStart
$ b>
/ code>和 selectionEnd
属性,以及。 IE不支持 window.getSelection()
,所以这段代码可以在你原来的代码所用的所有浏览器中工作。
I have a contenteditable div, like so:
<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>
for which I use the following code:
<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>
Clicking on the button when I move the caret around in the div, returns to me the actual position (offset) of the caret within the div.
The problem is when I replace the contenteditable div with an input type=text or password control, and keep the contenteditable property=true, and click on the button, I always get a zero. Why is this?
Thanks for looking.
解决方案 In most browsers, window.getSelection()
only works with selections within text nodes and elements within the document. It doesn't apply to text within <input>
and <textarea>
elements (although in WebKit window.getSelection().toString()
will return the selected text within a focussed text input or textarea. See http://jsfiddle.net/PUdaS/). To get the selection within an input, use the input's selectionStart
and selectionEnd
properties:
<input type="text" id="test" value="Some text">
<input type="button" value="Click me"
onclick="alert(document.getElementById('test').selectionEnd);">
Note that IE up to and including version 8 does not support the selectionStart
and selectionEnd
properties, and a different, more complicated solution is required. IE doesn't support window.getSelection()
either, so this code will work in all the browsers your original code does.
这篇关于如何让window.getselection为输入类型=文本字段工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!