问题
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 of the selected text's starting and ending points but I am having problems re-creating the range (so i can manipulate it). "quotables" is the div that holds all the text. I dont know what I am doing wrong.
var theRange = rangy.createRange();
var node = $('.quotables').html();
theRange.setStart(node, 14);
theRange.setEnd(node, 318);
but I keep getting errors:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
m.setStart
(anonymous function)
d.extend._Deferred.f.resolveWith
d.d.extend.ready
d.c.addEventListener.y
回答1:
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 |
:
<div id="test">foo|bar<br>|<br></div>
... the range's start boundary lies at offset 3 in the text node that is the first child of the <div>
element, while the end boundary lies at offset 2 within the <div>
, since there are two child nodes (text node "foobar" and one <br>
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);
来源:https://stackoverflow.com/questions/6935786/how-do-i-create-a-range-object-when-i-know-just-the-character-offsets