当我只知道字符偏移量时,如何创建范围对象?
所以我有一个包含文本块的 div,之前用户已在该块中选择了一些文本,并且我从该选择中创建了一个范围对象。我存储了所选文本的起点和终点的偏移量,但在重新创建范围时遇到问题(以便我可以操纵它)。 “quotables”是保存所有文本的 div。我不知道我做错了什么。
var theRange = rangy.createRange();
var node = $('.quotables').html();
theRange.setStart(node, 14);
theRange.setEnd(node, 318);
但我不断收到错误: 未捕获的错误:NOT_FOUND_ERR:DOM 异常 8
m.setStart
(匿名函数)
d.extend._Deferred.f.resolveWith
ddextend.ready
dcaddEventListener.y
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
范围边界不是 HTML 字符串表示形式中的字符偏移量。相反,它是 DOM 节点内的偏移量。例如,如果节点是文本节点,则边界表示为节点文本内的字符偏移量。如果该节点是一个元素,则表示为该节点在边界之前的子节点数。例如,在以下 HTML 中,范围的边界由
|
表示:...范围的起始边界位于文本节点中的偏移量 3 处,该文本节点是
的第一个子节点
元素,而结束边界位于
内的偏移量 2 处,因为有两个子节点(文本节点“foobar”和一个
< ;br>
元素)位于边界之前。您可以按如下方式以编程方式创建范围: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
|
:... 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: