简体   繁体   English

文本范围重叠的解决方案。

[英]Solution with overlapping text ranges.

I have a following problem and looking for hints how to do this with rangy or native range object. 我有一个以下问题,正在寻找有关如何使用范围对象或本机范围对象进行操作的提示。 I have div element that containing following text: "This is example text." 我的div元素包含以下文本:“这是示例文本。” From service I receiving this example json response. 从服务中,我收到此示例json响应。 [{ start: 0, end: 10}, {start: 2, end: 8}] I want to add spans that marks text from 0 to 10 and from 2 to 8. So second span - from 2 to 8 must be added with deviation of the already added span. [{开始:0,结束:10},{开始:2,结束:8}]我想添加将文本标记为从0到10和从2到8的跨度。因此,必须添加第二个跨度-从2到8与已添加跨度的偏差。

Best regards. 最好的祝福。

Rangy 1.3 has simple character offset-based getting and setting in the core via getBookmark() and moveToBookmark() methods of Range. Rangy 1.3通过getBookmark()moveToBookmark()方法在核心中具有基于字符偏移的简单获取和设置。 Once you have a range you can split text nodes at the range boundaries, get all the text nodes in the range using getNodes() and surround each in turn in a span. 有了范围后,您可以在范围边界处分割文本节点,使用getNodes()获取范围内的所有文本节点,然后依次将每个文本节点包围在一个范围内。

Demo: http://jsfiddle.net/mL0jz0xg/ 演示: http//jsfiddle.net/mL0jz0xg/

Code: 码:

function highlightCharacterRange(el, start, end) {
    var range = rangy.createRange();
    range.moveToBookmark({
        containerNode: el,
        start: start,
        end: end
    });
    range.splitBoundaries();
    var textNodes = range.getNodes([3]);
    for (var i = 0, textNode, span; textNode = textNodes[i++]; ) {
        span = document.createElement("span");
        span.className = "highlight";
        textNode.parentNode.insertBefore(span, textNode);
        span.appendChild(textNode);
    }
}

var container = document.getElementById("container");
highlightCharacterRange(container, 0, 10);
highlightCharacterRange(container, 2, 8);
highlightCharacterRange(container, 7, 14);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM