如何告知所有者选择?

如何判断选择的父节点是谁?

我正在选择:

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。

以下内容将返回所有主流浏览器中所选内容的父元素 ,并带有以下警告:

  • 获取父节点 (可以是任何类型,但最常见的是文本节点)在大多数浏览器上都很容易,但在IE <9中很棘手。如果你需要这样做,有像我自己的Rangy这样的库提供DOM所有主流浏览器的范围和选择支持。
  • 以下function仅考虑选择中的第一个范围。 Firefox是唯一支持多种选择的主流浏览器; 只考虑第一个。

码:

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

尝试$(':contains(' + selectedText + ')').parent() 。 那样有用吗?