Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

javascript - How do I get window.getselection to work for an input type=text field

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...