当我只知道字符偏移时,如何创建范围对象?
所以我有一个包含文本块的 div,之前用户在这个块中选择了一些文本,我从这个选择中创建了一个范围对象.我存储了所选文本的起点和终点的偏移量,但我在重新创建范围时遇到了问题(所以我可以操纵它)."quotables" 是包含所有文本的 div.我不知道我做错了什么.
<上一页><代码>var theRange = rangy.createRange();var node = $('.quotables').html();theRange.setStart(节点, 14);theRange.setEnd(节点,318);代码>但我不断收到错误:未捕获的错误:NOT_FOUND_ERR:DOM 异常 8
m.setStart
(匿名函数)
d.extend._Deferred.f.resolveWith
d.d.extend.ready
d.c.addEventListener.y
范围边界不是 HTML 字符串表示中的字符偏移.相反,它是 DOM 节点内的偏移量.例如,如果节点是文本节点,则边界表示为节点文本内的字符偏移量.如果节点是元素,则表示为边界之前节点的子节点数.例如,在以下 HTML 中,其边界由 |
表示:
<div id="test">foo|bar<br>|<br></div>
... 范围的起始边界位于作为 <div>
元素的第一个子元素的文本节点中的偏移量 3 处,而结束边界位于 中的偏移量 2 处><div>
,因为在边界之前有两个子节点(文本节点foobar"和一个 <br>
元素).您可以按如下方式以编程方式创建范围:
var range = rangy.createRange();//如果不使用 Rangy,则 document.createRange()var div = document.getElementById("test");range.setStart(div.firstChild, 3);range.setEnd(div, 2);
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
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);
相关文章