浏览器中范围和选择之间的区别
我想知道 JavaScript 中范围和选择对象之间的区别。
在我看来,您可以从这两者中获得相同的功能。在什么情况下您知道使用两者中的哪一个?
I wanted to know the difference between the range and the selection object in JavaScript.
It appears to me that you could get the same functionality out of either of these two. In which case are there are any specific circumstances where you know which of the two to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根本区别在于,
Selection
表示用户的选择,而Range
表示文档独立于任何视觉表示的连续部分。Selection
可以(几乎)用零个、一个或多个Range
来表示,但也可以完全独立于选择来创建和修改 Range。功能上存在一些重叠:例如,
Selection
的deleteFromDocument()
相当于在其所有组件 Range 上调用deleteContents()
,您可以使用anchorNode
、anchorOffset
、focusNode
和focusOffset< 获取选择中最近选择的范围的边界/代码> 属性。但是,存在一些关键差异:
Selection
可能包含多个范围。然而,目前唯一支持此功能的主要浏览器是 Firefox。Selection
可能是“向后”的,我的意思是选择的结束边界(由focusNode
和focusOffset
表示)可能会更早出现文档中的起始边界(anchorNode
和anchorOffset
)。 Range 没有方向。toString()
的工作方式有所不同。在大多数浏览器中(尤其是 IE 9 除外),在Selection
对象上调用toString()
仅返回所选的可见文本,而调用toString()范围上的
将返回范围内所有文本节点的串联,包括元素内的文本节点和通过 CSS 隐藏的元素。
The fundamental difference is that a
Selection
represents the user's selection, whileRange
represents a continuous part of a document independently of any visual representation. ASelection
can (almost) be expressed in terms of zero, one or moreRange
s but Ranges can also be created and modified completely independently of the selection.There is some overlap in functionality: for example,
Selection
'sdeleteFromDocument()
is equivalent to callingdeleteContents()
on all of its component Ranges, and you can get the boundaries of the most recently selected Range in the selection using theanchorNode
,anchorOffset
,focusNode
andfocusOffset
properties. However, there are some crucial differences:Selection
may contain multiple Ranges. However, the only major browser to support this currently is Firefox.Selection
may be "backwards", by which I mean that the end boundary of the selection (represented byfocusNode
andfocusOffset
) may occur earlier in the document than the start boundary (anchorNode
andanchorOffset
). A Range has no direction.toString()
works differently. In most browsers (although notably not IE 9), callingtoString()
on aSelection
object returns only the visible text that is selected, while callingtoString()
on a Range will return a concatenation of all text nodes within the range, including those within<script>
elements and elements hidden via CSS.