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

Koe*_*ong 14 javascript bookmarklet

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

例如:

<div id="some-id">to be highlighted</div>
Run Code Online (Sandbox Code Playgroud)

小书签代码:

javascript:(function(){alert(window.getSelection();})()
Run Code Online (Sandbox Code Playgroud)

如果我突出显示"要突出显示"文本,然后单击书签,它将提醒文本.但是我怎样才能获得文本所在的元素,在这种情况下是之后的元素?

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

谢谢!

Ein*_*eki 26

尝试类似于此的东西来获取包含所选文本的dom元素.

window.getSelection().anchorNode.parentNode
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

document.selection.createRange().parentElement();
Run Code Online (Sandbox Code Playgroud)

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


Tim*_*own 9

您可以在所有主流浏览器中相对简单地完成此操作 代码如下,实例: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
    };
}
Run Code Online (Sandbox Code Playgroud)