当我只知道字符偏移量时,如何创建范围对象? [英] How do I create a range object when I know just the character offsets?

查看:151
本文介绍了当我只知道字符偏移量时,如何创建范围对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);


但是我收到错误:
未捕获错误: NOT_FOUND_ERR:DOM异常8

m.setStart

(匿名函数)

d.extend._Deferred.f.resolveWith

ddextend.ready ???
dcaddEventListener.y

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

推荐答案

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

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>

...范围的起始边界位于文本节点的偏移量3,该节点是第一个< div> 元素,而结束边界位于< div> 之间的偏移量2处,因为那里是位于边界之前的两个子节点(文本节点foobar和一个< br> 元素)。您将以如下方式创建范围:

... 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);

这篇关于当我只知道字符偏移量时,如何创建范围对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆