简体   繁体   English

获取.html()和.text()中突出显示的文本位置

[英]Get the highlighted text position in .html() and .text()

I am using the following script to get the position of highlighted text: 我使用以下脚本来获取突出显示的文本的位置:

function getSelectionCharOffsetsWithin(element) {
    var start = 0, end = 0;
    var sel, range, priorRange;
    if (typeof window.getSelection != "undefined") {
        range = window.getSelection().getRangeAt(0);
        priorRange = range.cloneRange();
        priorRange.selectNodeContents(element);
        priorRange.setEnd(range.startContainer, range.startOffset);
        start = priorRange.toString().length;
        end = start + range.toString().length;
    } else if (typeof document.selection != "undefined" &&
        (sel = document.selection).type != "Control") {
        range = sel.createRange();
        priorRange = document.body.createTextRange();
        priorRange.moveToElementText(element);
        priorRange.setEndPoint("EndToStart", range);
        start = priorRange.text.length;
        end = start + range.text.length;
    }
    return {
        start: start,
        end: end
    };
  }

function alertSelection() {
    var mainDiv = document.getElementById("detailBoxParagraph");
    var sel = getSelectionCharOffsetsWithin(mainDiv);
    alert(sel.start + ": " + sel.end);
}

Now, if i use this on $('p').text() , which contains 现在,如果我在$('p').text() ,其中包含

Lorem ipsum dolor sit amet, consetetur sadipscing elitr. Lorem ipsum dolor 坐在 amet,consetetur sadipscing elitr。

everything works just fine. 一切正常。 But i also need to get the position in $ ('p').html() which is obviously different because of the <b> tag 但我还需要在$ ('p').html()中获得该位置,因为<b>标签显然不同

Lorem ipsum dolor `<b>sit</b>` amet, consetetur sadipscing elitr.

How do i prevent or change this? 我该如何预防或改变这个?

Edit: 编辑:

I forgot to say, my first thought was to count the times the tag occures, then use that value to calculate the new position, but this is idiotic somehow. 我忘了说,我的第一个想法是计算标签出现的次数,然后使用该值来计算新的位置,但这在某种程度上是愚蠢的。

My second approach was to replace the tag with an asterisk for the work with .text() 我的第二种方法是使用星号替换标记以使用.text()

Edit #2 编辑#2

Here is a messy fiddle showing the problem. 这是一个显示问题的混乱小提琴。 If you highlight text with the mouse, then click the button, the first time it will correctly be set to bold. 如果使用鼠标突出显示文本,则单击该按钮,第一次将其正确设置为粗体。 Second time won't work correctly. 第二次无法正常工作。

I will clean the fiddle up soon 我很快就会清理小提琴

http://jsfiddle.net/UpLaw/2/ http://jsfiddle.net/UpLaw/2/

Edit #3 编辑#3

i played around a little with the highlight plugin mentioned below but i wasn't able to limit the function to affect only the marked string. 我使用下面提到的高亮插件玩了一下,但我无法限制功能只影响标记的字符串。 It will either highlight all matching words or just the first appearence. 它将突出显示所有匹配的单词或仅突出显示第一个外观。 Can anyone help? 有人可以帮忙吗?

Here is the necessary code: 这是必要的代码:

jQuery.fn.highlight = function(pat) {
this.length = 1 ;

function innerHighlight(node, pat) {

    var skip = 0;
    if (node.nodeType == 3) {
        var pos = node.data.toUpperCase().indexOf(pat);
        if (pos >= 0) {
            var spannode = document.createElement('span');
            spannode.className = 'highlight';
            var middlebit = node.splitText(pos);
            var endbit = middlebit.splitText(pat.length);
            var middleclone = middlebit.cloneNode(true);
            spannode.appendChild(middleclone);
            middlebit.parentNode.replaceChild(spannode, middlebit);
            skip = 1;
        }
    }
    else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {

        for (var i = 0; i < 1; ++i) { // So it will highlight only the first occurence. 
            i += innerHighlight(node.childNodes[i], pat);
        }
    }
    return skip;
}
return this.length && pat && pat.length ? this.each(function() {
    innerHighlight(this, pat.toUpperCase());

}) : this;
};

Edit #4 编辑#4

Okay, i tried to understand that javscript. 好的,我试着理解javscript。 As far as i see, this can not be done since highlight() is called with a simple string as a parameter. 据我所知,由于使用简单的字符串作为参数调用highlight(),因此无法完成此操作。 It can not know the position of this string. 它无法知道这个字符串的位置。 Could / Should i parse the position, then try to search from that position, highlight the first occurence, then abort? 可能/我应该解析位置,然后尝试从该位置搜索,突出显示第一次出现,然后中止?

From your comment, this is what you want to accomplish. 从您的评论中,这是您想要完成的。

i will try to explain this as good as i can. 我会尽力解释这个问题。 English is not my native language, so sorry for the confusion. 英语不是我的母语,对于这种混乱感到抱歉。 I would like to insert a html-tag before and after the highlighted text. 我想在突出显示的文本之前和之后插入一个html标记。 To achieve this, i will have to get the beginning and end of the text. 要实现这一点,我必须得到文本的开头和结尾。

Assuming sit is the highlighted selection you want to process. 假设sit是您要处理的突出显示的选择。

You can use .wrap() or .after() and .before() to accomplish this. 您可以使用.wrap()或.after()和.before()来完成此任务。

function alertSelection() {
    $("b", $('#detailBoxParagraph')).wrap('<i/>'); // make the  highlighted section inside a tag.

    $("b", $('#detailBoxParagraph')).before('<u>Content inserted before </u> '); // insert an html before highlighted selections.

    $("b", $('#detailBoxParagraph')).after(' <u>Content inserted after </u>'); // insert an html after highlighted selections.
}

$(function () {
    alertSelection();
})

Here I'm making the highlighted text italics. 在这里,我将突出显示的文本设为斜体。

See sample in jsFiddle 请参阅jsFiddle中的示例

Reference 参考


If you are trying to accomplish the selected text to highlight, you can use jQuery highlight plugin. 如果您尝试完成所选文本以突出显示,则可以使用jQuery高亮插件。

See sample in jsFiddle. 请参阅jsFiddle中的示例

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

$(function () {
    $('#detailBoxParagraph').mouseup(function (e){
        $(this).removeHighlight();
        $(this).highlight(getSelectionText());
   });
});

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

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