如何判断选择的父节点是谁?
我正在选择:
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。
答案 0 :(得分:0)
试试$(':contains(' + selectedText + ')').parent()
。这有用吗?
答案 1 :(得分:0)
以下内容将返回所有主流浏览器中所选内容的父元素,并带有以下警告:
代码:
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;
}