简体   繁体   English

如何获取window.getSelection()的范围对象?

[英]How to obtain range object for window.getSelection()?

In a js function, I want to obtain all Nodes(HTML elements) that are part of the content in a web page, when the content has been selected by the user. 在js函数中,当用户选择了内容时,我希望获取属于网页内容一部分的所有节点(HTML元素)。

Now, I understand that window.getSelection() will give me a selection object. 现在,我明白window.getSelection()会给我一个选择对象。 Also, this selection object has to be converted into a range object, before I can obtain the list of nodes(HTML elements) that are part of that selection. 此外,在我可以获得作为该选择的一部分的节点列表(HTML元素)之前,必须将该选择对象转换为范围对象。

How do I obtain the range object? 我如何获得范围对象? From what i read, different browsers have different implementations of range objects...Initially, I will use this js function only in Google Chrome...So code should work perfectly in Google Chrome... but I do want that the code works across all/most new versions of Google Chrome... The code may be JS or pure Jquery. 从我读到的,不同的浏览器有不同的范围对象实现...最初,我将只在谷歌Chrome中使用这个js功能...所以代码应该在谷歌Chrome中完美运行...但我确实希望代码有效跨所有/大多数新版Google Chrome ...代码可能是JS或纯Jquery。

One more question-- do I have to use a js library like "Rangy"- http://code.google.com/p/rangy/ for this purpose? 还有一个问题 - 为此,我是否必须使用像“Rangy”这样的js库 - http://code.google.com/p/rangy/ Or can this be achieved using pure js or jquery code? 或者这可以使用纯js或jquery代码实现吗?

Apart from IE < 9, all major browsers implement the same standards for Selection and Range and have done for years. 除了IE <9之外,所有主流浏览器都对选择和范围实施相同的标准并且已经做了多年。 There are some differences but the APIs are the same. 存在一些差异,但API是相同的。 If you're not bothered about IE < 9 then you really don't need to use Rangy (it's around 40KB before gzipping), although it does have a convenient method for getting nodes that you may find helpful. 如果你对IE <9不感兴趣,那么你真的不需要使用Rangy(在gzipping之前它是大约40KB),虽然它确实有一个方便的方法来获取你可能会觉得有用的节点。

To get the nodes within the selection, you can get the selected range like this: 要获取选择范围内的节点,您可以获得所选范围,如下所示:

var sel = window.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
}

To get the nodes from the range, you could use the code from this answer . 要从范围中获取节点,您可以使用此答案中的代码。 If you used Rangy, it would be 如果您使用Rangy,那就是

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var nodes = range.getNodes();
}

I can see the problem that you are facing is not to get a range object but to find the HTML nodes inside the selection. 我可以看到您面临的问题不是获取范围对象,而是查找选择内的HTML节点。 In this demo , if you select text and click 'get selection html' button, you get the selected text including the DOM. 本演示中 ,如果您选择文本并单击“获取选择html”按钮,则会获得包含DOM的选定文本。 Once you get that, you can find a list of DOM nodes using jquery code. 一旦你得到它,你可以使用jquery代码找到DOM节点列表。 Let me know if you need more info on this. 如果您需要更多信息,请与我们联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM