get start point and end point of user selection
I am trying to get the starting and ending points of user selection. This is the content of a DIV that I have
abc def ghi jkl mno pqr stuv wxyz
When I select pqr
The starting point becomes 1 and the ending point becomes 4 which is wrong
When I select the whole thing, the starting point becomes 0 and the ending point becomes 33 which is right
I have the following code:
sel = window.getSelection();
le = sel.toString().length;
if (sel.getRangeAt && sel.rangeCount)
{
range = window.getSelection().getRangeAt(0);
开发者_开发知识库 sp = range.startOffset;
ep = sp + le;
}
Rangy to the rescue! Use this api to get everything about user selection.
It supports browser:
- Internet Explorer 6 and later (:D)
- Firefox 2.0 and later
- Google Chrome 5.0 and later
- Safari 3.2 and later
- Opera 9.6 and later
Using it
Read the documentation yourself, or just use the below.
Very simple (in your case),
var selection = rangy.getSelection(), //Whole lot of information, supports
//multi-selections
start=selection.anchorOffset, //Start position
end=selection.focusOffset; //End position
Hope it helps you out.
Demos
You can find demos on its home page.
Here are some that might help you out and might find interesting:
- Demo 1 - Core, the main thing
- Demo 4 - Change the CSS of the selected range
- Demo 3 - Serializing selection(s)
精彩评论