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

时间:2011-01-09 00:08:44

标签: javascript bookmarklet

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

例如:

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

小书签代码:

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

如果我突出显示“要突出显示”文本,然后单击书签,它将提醒文本。但是,如何获取文本所在的元素,在这种情况下是后面的元素?

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

谢谢!

3 个答案:

答案 0 :(得分:22)

尝试类似于此的内容以获取包含所选文本的dom元素。

window.getSelection().anchorNode.parentNode

它适用于firefox和Chorme,您应该将其测试到剩余的浏览器中。

它有一个怪癖,如果你选择的文字不仅仅是一个元素,那么只返回第一个。但也许你可以忍受这个。

仅供参考什么是anchorNode属性: http://help.dottoro.com/ljkstboe.php

在Internet Explorer上,这个代码片段可以解决问题(我无法测试)

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

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

关于quirksmode的范围说明:http://www.quirksmode.org/dom/range_intro.html

答案 1 :(得分:7)

您可以在所有主流浏览器中相对简单地执行此操作。代码如下,实例: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
    };
}

答案 2 :(得分:0)

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

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

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

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

它将存储在selectedElement

好的尝试这个:

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/ 更好的是:http://jsfiddle.net/HQC6Z/

在查看其他答案之后,我收回了我的解决方案并提供了他们的解决方案:

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

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

相关问题