JQuery:如何根据给定的偏移量减少选定的节点

时间:2013-12-27 20:12:25

标签: javascript jquery dom

我正在使用JQuery(也是DOM API)来选择文本节点。一旦我选择了文本节点,我需要再次根据字符数(偏移量)重新选择。我不知道该怎么做。

示例代码:

var jCommentElm = jQuery("#345345"); //Select the original text
var finalSelectedComment = Not sure how to do?;          //Apply offset to select limited chars as per given count
finalSelectedComment .addClass("commentedtext"); //Apply CSS to highlight

修改 以下是我用来添加评论的示例标记。我有评论的起始标记和偏移。我使用起始标记在标记之后选择完整的文本,现在我想根据偏移减少我的选择。

<p > This is sample text. Few <?comment_marker 4?>chars may be selected together and mark as comment</p>

请帮忙。

1 个答案:

答案 0 :(得分:0)

试试这个(jsfiddle):

HTML:

<p>This is sample text. Few <span data-chars="4"></span>chars may be selected together and mark as comment</p>


CSS:

.hi {
    background: yellow;    
}


jQuery的:

selectText('p');

function selectText(el) {
    var el = $(el),
        charEl = el.children("span[data-chars]"),
        chars = parseInt(charEl.attr('data-chars')), //4
        html = el.html(),
        regex = /\<span data-chars=\"\d+\"\>\<\/span\>/gi,
        index = html.search(regex),
        newStr = html.replace(regex,''),
        beg = newStr.substr(0,index),
        mid = newStr.substr(index,chars),
        end = newStr.substr(index + chars);

    el.html(beg + '<span class="hi">'+mid+'</span>' + end);

}
  1. 这将寻找一个空的SPAN(充当'标记'),其中HTML5 data- *元素包含您想要突出显示的多个字符,从该SPAN之后开始。

  2. 然后缓存标记的索引,删除标记,将原始字符串切割为标记索引的起始部分,标记索引的一部分加上要选择的字符数,以及然后是结束部分。

  3. 然后将这三个部分重新组合回您的父元素的innerHTML,其中间部分由不同的SPAN包裹,类别为“hi”(“highlight”的缩写),具有背景色“黄色”的属性(或您喜欢的任何颜色)。

  4. CONS
    o空白计为字符
    o可能有点挑剔回去然后删除$('。hi')