开发者

get start point and end point of user selection

开发者 https://www.devze.com 2023-04-04 18:36 出处:网络
I am trying to get the starting and ending points of user selection. This is the content of a DIV that I have

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:

  1. Internet Explorer 6 and later (:D)
  2. Firefox 2.0 and later
  3. Google Chrome 5.0 and later
  4. Safari 3.2 and later
  5. 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消