How do I create a range object when I know just the character offsets?

后端 未结 1 392
栀梦
栀梦 2020-12-28 20:41

So I have a div that contains a block of text, previously the user has selected some text in this block and I created a range object from this selection. I stored the offset

1条回答
  •  隐瞒了意图╮
    2020-12-28 21:35

    A Range boundary is not a character offset within a string representation of HTML. Rather, it is an offset within a DOM node. If the node is a text node, for example, the boundary is expressed as a character offset within the node's text. If the node is an element, it is expressed as the number of child nodes of the node prior to the boundary. For example, in the following HTML, with a Range whose boundaries are denoted by |:

    foo|bar
    |

    ... the range's start boundary lies at offset 3 in the text node that is the first child of the

    element, while the end boundary lies at offset 2 within the
    , since there are two child nodes (text node "foobar" and one
    element) lying before the boundary. You would create the range programmatically as follows:

    var range = rangy.createRange(); // document.createRange() if not using Rangy
    var div = document.getElementById("test");
    range.setStart(div.firstChild, 3);
    range.setEnd(div, 2);
    

    0 讨论(0)
提交回复
热议问题