简体   繁体   English

document.getSelection 返回的对象中的 anchorNode 、 baseNode 、 extentNode 和 focusNode 是什么?

[英]What is anchorNode , baseNode , extentNode and focusNode in the object returned by document.getSelection?

If I make a selection in a html page and I do :如果我在 html 页面中进行选择并且我这样做:

var a = document.getSelection()

I get an object with four properties :我得到一个具有四个属性的对象:

  1. anchorNode锚节点
  2. baseNode基节点
  3. extentNode范围节点
  4. focusNode焦点节点

the values of first three is the same ie the text that I have selected but how are they different and which one to use?前三个的值是相同的,即我选择的文本,但它们有何不同以及使用哪一个?

According to MDN根据MDN

selection.anchorNode - returns the Node in which the selection begins. selection.anchorNode - 返回选择开始的节点。

selection.focusNode - returns the Node in which the selection ends. selection.focusNode - 返回选择结束的节点。

because there were debates on naming:因为有关于命名的争论:

  • baseNode is alias for anchorNode baseNodeanchorNode别名
  • extentNode for focusNode焦点节点的范围节点

Note: references to both baseNode and extentNode have been removed from the MDN page.注意:对baseNodeextentNode引用已从 MDN 页面中删除。

The following is beyond the scope of this question, but I'll post this anyway, as I found selection to be a tricky part in some scenarios.以下内容超出了这个问题的范围,但无论如何我都会发布这个,因为我发现在某些情况下选择是一个棘手的部分。

Take a look at this example:看看这个例子:

<p>ab12<sup>3</sup>4567890 !</p>

Let's say we've made selection "1234567890".假设我们选择了“1234567890”。 I've made a picture to explain where anchor and focus nodes and offsets are.我制作了一张图片来解释锚点和焦点节点以及偏移量的位置。

窗口.getSelection

I have been building out a feature that requires nested contenteditable elements.我一直在构建一个需要嵌套的 contenteditable 元素的功能。 When debugging I noticed that baseNode and extentNode are NOT just aliases.调试时我注意到baseNode和extentNode只是别名。 I am trying to find documentation on them since they are not in MDN.我正在尝试查找有关它们的文档,因为它们不在 MDN 中。 But based on this screenshot I wouldn't assume they are just aliases (in Chrome):但基于此屏幕截图,我不会假设它们只是别名(在 Chrome 中): 在此处输入图片说明

I'm by no means an expert, but by experimenting it seems to me that the anchorNode is the node the selection started on and focusNode the one where it ended (presumably because it has focus once the selection is over).我绝不是专家,但通过实验在我看来,anchorNode 是选择开始的节点,而 focusNode 是结束的节点(大概是因为一旦选择结束它就有焦点)。

baseNode seems to be the same as anchorNode and extentNode the same as baseNode, only that they don't exist in Firefox, only in Chrome. baseNode 似乎与 anchorNode 相同,extentNode 与 baseNode 相同,只是它们在 Firefox 中不存在,仅在 Chrome 中存在。

anchorNode and focusNode - there are in every browser. anchorNode 和 focusNode - 每个浏览器都有。 baseNode and extentNode - there are only in Chrome baseNode 和 extentNode - 只有在 Chrome 中有

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

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