如何知道所选文本是否在特定div中

sri*_*ath 7 html javascript dom

我有两个div,如下所示:

<div id="div1">
<p>something</p>
<div><table><tr><td>Div1</td></tr></table></div>
</div>
<div id="div2">
<p>something else</p>
<div><table><tr><td>Div2</td></tr></table></div>
</div>
<button type="button">Check</button>
Run Code Online (Sandbox Code Playgroud)

现在,我想知道何时选择某些文本,然后按下按钮,如果所选文本在"div1"下面.我怎样才能做到这一点?

编辑:解决方案必须在IE-7及更高版本中工作.

Tim*_*own 19

elementContainsSelection()下面的函数返回一个布尔值,表示指定的元素是否包含整个用户的选择,并适用于所有主流浏览器,包括IE 6.

现场演示:http://jsfiddle.net/eT8NQ/

码:

function isOrContains(node, container) {
    while (node) {
        if (node === container) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

function elementContainsSelection(el) {
    var sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            for (var i = 0; i < sel.rangeCount; ++i) {
                if (!isOrContains(sel.getRangeAt(i).commonAncestorContainer, el)) {
                    return false;
                }
            }
            return true;
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        return isOrContains(sel.createRange().parentElement(), el);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)