如何获得突出显示文本所在的元素?

时间:2022-05-25 06:39:52

I am trying to learn how to write a bookmarklet where I can highlight some text, click on the bookmarklet and have it tell me what got highlighted. I can get that far, but next I want to know what element that text is in.

我正在学习如何写一个书签,在那里我可以突出显示一些文本,点击书签,让它告诉我什么被突出显示。我可以做到这一点,但是接下来我想知道文本在哪个元素中。

For example:

例如:

<div id="some-id">to be highlighted</div>

The bookmarklet code:

书签的代码:

javascript:(function(){alert(window.getSelection();})()

If I highlight the text "to be highlighted" and then click on the bookmarklet, it will alert the text. But how can I get the element in which the text is in, in this case the element after that?

如果我突出显示“要突出显示”的文本,然后单击bookmarklet,它将通知文本。但是我如何得到文本所在的元素,在这个例子中是元素之后呢?

So the flow is: highlight text, click bookmarklet, bookmarklet tells you what you highlighted and the element it's in.

所以流程是:突出显示文本,单击bookmarklet, bookmarklet告诉您突出显示的内容以及它所在的元素。

Thanks!

谢谢!

3 个解决方案

#1


21  

Try something similar to this to get the dom element that contains the selected text.

尝试类似的方法来获取包含所选文本的dom元素。

window.getSelection().anchorNode.parentNode

It works on firefox and Chorme, you should test it into the remaining browsers.

它可以在firefox和Chorme上使用,您应该在其他浏览器中进行测试。

It have a quirk, if you select text that beholds to more than an element, only the first one is returned. But maybe you can live with this.

它有一个怪癖,如果您选择的文本包含的元素不止一个,那么只返回第一个元素。但也许你可以接受。

Just for reference on what is the anchorNode property: http://help.dottoro.com/ljkstboe.php

只是为了参考主播节点的属性:http://help.dottoro.com/ljkstboe.php

On internet explorer this snippet should do the trick (I can't test it)

在internet explorer中,这段代码应该可以实现这个功能(我不能测试它)

document.selection.createRange().parentElement();

as stated into http://msdn.microsoft.com/en-us/library/ms535872.aspx and http://msdn.microsoft.com/en-us/library/ms536654.aspx

如http://msdn.microsoft.com/en-us/library/ms535872.aspx和http://msdn.microsoft.com/en-us/library/ms536654.aspx所述

A range explanation on quirksmode: http://www.quirksmode.org/dom/range_intro.html

关于quirksmode的范围解释:http://www.quirksmode.org/dom/range_intro.html

#2


6  

You can do this relatively simply in all major browsers. Code is below, live example: http://jsfiddle.net/timdown/Q9VZT/

您可以在所有主流浏览器中相对简单地完成此操作。代码如下,实时示例:http://jsfiddle.net/timdown/Q9VZT/

function getSelectionTextAndContainerElement() {
    var text = "", containerElement = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var node = sel.getRangeAt(0).commonAncestorContainer;
            containerElement = node.nodeType == 1 ? node : node.parentNode;
            text = sel.toString();
        }
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        containerElement = textRange.parentElement();
        text = textRange.text;
    }
    return {
        text: text,
        containerElement: containerElement
    };
}

#3


0  

I don't think you can, he only way to know which element is currently being used would be to use a onclick event on the element. Other than that there is no sure way. You can however search each element until you find an element with the same text,

我不认为你可以,他唯一知道当前使用哪个元素的方法是在元素上使用onclick事件。除此之外,没有确定的方法。但是你可以搜索每个元素,直到找到一个文本相同的元素,

jQuery('*:contains(' + selected + ').

You can add an event to get the current element with this code though (untested)

您可以添加一个事件来使用此代码获取当前元素(未经测试)

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e){
        window.selectedElement = all[i];
        //preventDefault $ StopBubble &
        return false;
    }

And it will be stored in selectedElement

它将存储在selectedElement中。

Ok try This:

可以试试这个:

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e) {
        window.selectedElement = this;
        ((e && e.stopPropagation && e.stopPropagation()) ||
         (window.event && (window.event.cancelBubble = true)));
        return false;
    }

DEMO: http://jsfiddle.net/HQC6Z/1/ Better yet: http://jsfiddle.net/HQC6Z/

演示:http://jsfiddle.net/HQC6Z/1/更好:http://jsfiddle.net/HQC6Z/

After looking at the other answers, I take back my solution and offer theirs:

看完其他答案后,我收回我的答案,并给出他们的答案:

How can I get the element in which highlighted text is in?

如何获得突出显示文本所在的元素?

How can I get the element in which highlighted text is in?

如何获得突出显示文本所在的元素?

#1


21  

Try something similar to this to get the dom element that contains the selected text.

尝试类似的方法来获取包含所选文本的dom元素。

window.getSelection().anchorNode.parentNode

It works on firefox and Chorme, you should test it into the remaining browsers.

它可以在firefox和Chorme上使用,您应该在其他浏览器中进行测试。

It have a quirk, if you select text that beholds to more than an element, only the first one is returned. But maybe you can live with this.

它有一个怪癖,如果您选择的文本包含的元素不止一个,那么只返回第一个元素。但也许你可以接受。

Just for reference on what is the anchorNode property: http://help.dottoro.com/ljkstboe.php

只是为了参考主播节点的属性:http://help.dottoro.com/ljkstboe.php

On internet explorer this snippet should do the trick (I can't test it)

在internet explorer中,这段代码应该可以实现这个功能(我不能测试它)

document.selection.createRange().parentElement();

as stated into http://msdn.microsoft.com/en-us/library/ms535872.aspx and http://msdn.microsoft.com/en-us/library/ms536654.aspx

如http://msdn.microsoft.com/en-us/library/ms535872.aspx和http://msdn.microsoft.com/en-us/library/ms536654.aspx所述

A range explanation on quirksmode: http://www.quirksmode.org/dom/range_intro.html

关于quirksmode的范围解释:http://www.quirksmode.org/dom/range_intro.html

#2


6  

You can do this relatively simply in all major browsers. Code is below, live example: http://jsfiddle.net/timdown/Q9VZT/

您可以在所有主流浏览器中相对简单地完成此操作。代码如下,实时示例:http://jsfiddle.net/timdown/Q9VZT/

function getSelectionTextAndContainerElement() {
    var text = "", containerElement = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var node = sel.getRangeAt(0).commonAncestorContainer;
            containerElement = node.nodeType == 1 ? node : node.parentNode;
            text = sel.toString();
        }
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        containerElement = textRange.parentElement();
        text = textRange.text;
    }
    return {
        text: text,
        containerElement: containerElement
    };
}

#3


0  

I don't think you can, he only way to know which element is currently being used would be to use a onclick event on the element. Other than that there is no sure way. You can however search each element until you find an element with the same text,

我不认为你可以,他唯一知道当前使用哪个元素的方法是在元素上使用onclick事件。除此之外,没有确定的方法。但是你可以搜索每个元素,直到找到一个文本相同的元素,

jQuery('*:contains(' + selected + ').

You can add an event to get the current element with this code though (untested)

您可以添加一个事件来使用此代码获取当前元素(未经测试)

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e){
        window.selectedElement = all[i];
        //preventDefault $ StopBubble &
        return false;
    }

And it will be stored in selectedElement

它将存储在selectedElement中。

Ok try This:

可以试试这个:

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e) {
        window.selectedElement = this;
        ((e && e.stopPropagation && e.stopPropagation()) ||
         (window.event && (window.event.cancelBubble = true)));
        return false;
    }

DEMO: http://jsfiddle.net/HQC6Z/1/ Better yet: http://jsfiddle.net/HQC6Z/

演示:http://jsfiddle.net/HQC6Z/1/更好:http://jsfiddle.net/HQC6Z/

After looking at the other answers, I take back my solution and offer theirs:

看完其他答案后,我收回我的答案,并给出他们的答案:

How can I get the element in which highlighted text is in?

如何获得突出显示文本所在的元素?

How can I get the element in which highlighted text is in?

如何获得突出显示文本所在的元素?