javascript 当我只知道字符偏移量时,如何创建范围对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6935786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:23:34  来源:igfitidea点击:

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

javascripthtmldomrangerangy

提问by Adim

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.

所以我有一个包含文本块的 div,以前用户在这个块中选择了一些文本,我从这个选择中创建了一个范围对象。我存储了所选文本的起点和终点的偏移量,但我在重新创建范围时遇到了问题(因此我可以操纵它)。“quotables”是包含所有文本的 div。我不知道我做错了什么。



    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

但我不断收到错误:未捕获的错误:NOT_FOUND_ERR:DOM Exception 8
m.setStart
(匿名函数)
d.extend._Deferred.f.resolveWith
ddextend.ready
dcaddEventListener.y

回答by Tim Down

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 |:

范围边界不是 HTML 字符串表示中的字符偏移量。相反,它是 DOM 节点内的偏移量。例如,如果节点是文本节点,则边界表示为节点文本内的字符偏移。如果节点是元素,则表示为该节点在边界之前的子节点数。例如,在下面的 HTML 中,一个 Range 的边界由 表示|

<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:

... 范围的起始边界位于作为<div>元素第一个子元素的文本节点中的偏移 3 处,而结束边界位于 中的偏移 2 处<div>,因为有两个子节点(文本节点“foobar”和一个<br>元素) 位于边界前。您将以编程方式创建范围,如下所示:

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