如何知道所选文本是否在特定 div 内 [英] How to know if selected text is inside a specific div

查看:36
本文介绍了如何知道所选文本是否在特定 div 内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 div,如下所示:

<p>某物</p><div><table><tr><td>Div1</td></tr></table></div>

<div id="div2"><p>别的东西</p><div><table><tr><td>Div2</td></tr></table></div>

<button type="button">检查</button>

现在,我想知道何时选择某些文本然后按下按钮,如果选定的文本在div1"下.我该怎么做?

该解决方案必须适用于 IE-7 及更高版本.

解决方案

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

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

代码:

function isOrContains(node, container) {而(节点){如果(节点 === 容器){返回真;}节点 = node.parentNode;}返回假;}函数 elementContainsSelection(el) {变量选择;如果(window.getSelection){sel = window.getSelection();如果(sel.rangeCount > 0){for (var i = 0; i < sel.rangeCount; ++i) {如果 (!isOrContains(sel.getRangeAt(i).commonAncestorContainer, el)) {返回假;}}返回真;}} else if ( (sel = document.selection) && sel.type != "Control") {返回 isOrContains(sel.createRange().parentElement(), el);}返回假;}

I have two divs as shown below:

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

Now, I want to know when some text is selected and then the button pressed, if the selected text is under "div1" or not. How can I do that?

Edit: And the solution has to work in IE-7 and above.

解决方案

The elementContainsSelection() function below returns a boolean representing whether the specified element contains the whole of the user's selection and works in all major browsers, including IE 6.

Live demo: http://jsfiddle.net/eT8NQ/

Code:

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

这篇关于如何知道所选文本是否在特定 div 内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆