js初学者-如何获得网页中所选内容的html以及整个节点层次结构

js beginner- how to get html for selected content in a web page along with entire node hierarchy for the selection

本文关键字:html 层次结构 节点 初学者 何获得 网页 js      更新时间:2024-03-13

Athttp://rangy.googlecode.com/svn/trunk/demos/core.html有一个演示展示了如何为用户选择的内容获取HTML。

然而,我也想获得节点的整个结构,从顶级节点到所选内容所属的节点。如何获取此节点结构?例如,请查看下面的样本内容

<div id="toplevelnotselectedbyuser">
<p id="thispisselectedbyuser">
This text is not selected by the user...
Some sample text that has been selected by user...
Some more text that has not been selected by the user.
</p>
</div>

现在,如果用户只选择内容"用户选择的某些示例文本…",并且如果使用我给出的上面的示例(使用"rangy"库),那么只有文本"用户选择了某些示例文本"显示为该库选择的HTML——我也想要div和p的信息。。。我该怎么做?我更喜欢jquery,但纯javascript或任何其他库也可以…

我不认为浏览器会根据DOM来考虑文本范围。如果这很容易,那么这个细长的工具可能会提供这些信息。您可能需要破解它,也许可以通过挂接到mouseup事件来确定选择结束时范围内的父元素。

我认为这将是一个昂贵的操作,但在jQuery中类似

$(document).on('mouseup','*',function(e) {
  console.log($(this));
  return false;
});​

在这种情况下,$(this)将是用户停止选择的DOM元素。我会通过使用适当的选择器而不是上面的document来尽可能地限制范围。

下面是一个jsFiddle(在控制台打开的情况下运行以查看结果):http://jsfiddle.net/8uzgt/2/