获取.html()和.text()中突出显示的文本位置 [英] Get the highlighted text position in .html() and .text()

查看:80
本文介绍了获取.html()和.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);
}

现在,如果我在 $(' p')。text(),其中包含

Now, if i use this on $('p').text(), which contains


Lorem ipsum dolor amet,consetetur sadipscing elitr。

Lorem ipsum dolor sit amet, consetetur sadipscing elitr.

一切正常。但我还需要获得$ ('p')。html()中的位置,这显然是不同的,因为< b> tag

everything works just fine. But i also need to get the position in $('p').html() which is obviously different because of the <b> tag

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

我如何阻止或更改此信息?

How do i prevent or change this?

编辑:

我忘了说,我的第一个想法是计算标签出现的次数,然后使用该值来计算新职位,但这在某种程度上是愚蠢的。

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.

我的第二种方法是用星号替换标签,用 .text()

My second approach was to replace the tag with an asterisk for the work with .text()

编辑#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.

我会尽快清理小提琴

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

编辑#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?

这是必要的代码:

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

编辑#4

好的,我试着理解javscript。据我所知,由于使用简单的字符串作为参数调用highlight(),因此无法完成此操作。它无法知道这个字符串的位置。可能/我应该解析位置,然后尝试从该位置搜索,突出显示第一次出现,然后中止?

Okay, i tried to understand that javscript. As far as i see, this can not be done since highlight() is called with a simple string as a parameter. 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.


我会尽力解释这个问题。英语不是我的母语,对于这种混乱感到抱歉。我想在突出显示的文本之前和之后插入一个html标记。要实现这一点,我必须得到文本的开头和结尾。

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

您可以使用.wrap()或.after()和.before()来完成此操作。

You can use .wrap() or .after() and .before() to accomplish this.

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.

参见 jsFiddle

参考

  • .wrap()
  • .before()
  • .after()

如果您要完成要突出显示的所选文本,可以使用 jQuery highlight 插件。

If you are trying to accomplish the selected text to highlight, you can use jQuery highlight plugin.

参见 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());
   });
});

这篇关于获取.html()和.text()中突出显示的文本位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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