获取所选文本的父元素

Mac*_*Mac 15 javascript jquery text

是否可以在页面中获取所选文本的父元素?例如:

<div class="someparent">

Selection of this text should refer to the 'someparent' class.

<span class="spanparent">If this is selected, the parent should be this span</span>

</div>
Run Code Online (Sandbox Code Playgroud)

因为在获取所选文本时,它通常从窗口或文档中获取它(取决于浏览器),但是可以获取所选文本的父元素吗?

Tim*_*own 38

这是一个函数,它将为您提供包含所有主要浏览器中所有用户选择的最内层元素(除非选择了多个范围,仅在Firefox中支持.如果这很重要,我可以扩展示例来处理那个案子也是):

function getSelectionParentElement() {
    var parentEl = null, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            parentEl = sel.getRangeAt(0).commonAncestorContainer;
            if (parentEl.nodeType != 1) {
                parentEl = parentEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        parentEl = sel.createRange().parentElement();
    }
    return parentEl;
}
Run Code Online (Sandbox Code Playgroud)


chi*_*iya 10

我建议用这个

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

我在safari osx 10.9中测试过