如何知道选择的文本是否在特定的div内 [英] How to know if selected text is inside a specific div
本文介绍了如何知道选择的文本是否在特定的div内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个div,如下所示:
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>
现在,我想知道什么时候选择了一些文本,然后按下按钮,如果所选的文本是否在div1下。如何做到这一点?
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?
编辑:解决方案必须适用于IE-7及以上版本。
And the solution has to work in IE-7 and above.
推荐答案
下面的 elementContainsSelection()
函数返回一个布尔值,表示指定的元素是否包含整个用户的选择,并在所有主要浏览器,包括IE 6。
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.
现场演示: 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;
}
这篇关于如何知道选择的文本是否在特定的div内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文