如何告知选择的所有者? [英] How can I tell the owner of a selection?
本文介绍了如何告知选择的所有者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么知道选区的父节点是谁?
How can I tell who the parent node of a selection is?
我正在选择:
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
else if (document.selection) {
userSelection = document.selection.createRange();
}
var selectedText = userSelection;
if (userSelection.text)
selectedText = userSelection.text;
但是我怎么知道谁是选区的父节点?也就是说,如果整个选择都来自一个div
,我想知道该div.
But how can i tell who's the parent node of the selection? That is, if the whole selection is from withing a single div
I want to know that div.
推荐答案
以下内容将在所有主要浏览器中返回所选内容的父元素 ,并附带以下警告:
The following will return the parent element of the selection in all major browsers, with the following caveats:
- 获取父节点(可以是任何类型,但最常见的是文本节点)反而在大多数浏览器中都很容易,但在IE中却很棘手. 9.如果您需要这样做,可以使用诸如我自己的 Rangy 之类的库来提供DOM范围.和对所有主要浏览器的选择支持.
- 以下功能仅考虑选择范围内的第一个范围. Firefox是唯一支持多种选择的主流浏览器.仅考虑第一个.
- Getting the parent node instead (which could be of any type but is most commonly a text node) is easy on most browsers but tricky in IE < 9. If you need to do this, there are libraries such as my own Rangy that provide DOM Range and Selection support for all major browsers.
- The function below only considers the first Range within the selection. Firefox is the only major browser that supports multiple selections; only the first is considered.
代码:
function getSelectionContainerElement() {
var container = null;
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
container = sel.getRangeAt(0).commonAncestorContainer;
if (container.nodeType != 1) {
container = container.parentNode;
}
}
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
container = document.selection.createRange().parentElement();
}
return container;
}
这篇关于如何告知选择的所有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文