浏览器中范围和选择之间的区别

发布于 2024-10-30 08:50:35 字数 86 浏览 3 评论 0原文

我想知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

下壹個目標 2024-11-06 08:50:35

根本区别在于,Selection 表示用户的选择,而 Range 表示文档独立于任何视觉表示的连续部分。 Selection 可以(几乎)用零个、一个或多个 Range 来表示,但也可以完全独立于选择来创建和修改 Range。

功能上存在一些重叠:例如,SelectiondeleteFromDocument() 相当于在其所有组件 Range 上调用 deleteContents() ,您可以使用 anchorNodeanchorOffsetfocusNodefocusOffset< 获取选择中最近选择的范围的边界/代码> 属性。但是,存在一些关键差异:

  • Selection 可能包含多个范围。然而,目前唯一支持此功能的主要浏览器是 Firefox。
  • Selection 可能是“向后”的,我的意思是选择的结束边界(由 focusNodefocusOffset 表示)可能会更早出现文档中的起始边界(anchorNodeanchorOffset)。 Range 没有方向。
  • toString() 的工作方式有所不同。在大多数浏览器中(尤其是 IE 9 除外),在 Selection 对象上调用 toString() 仅返回所选的可见文本,而调用 toString()范围上的 将返回范围内所有文本节点的串联,包括

The fundamental difference is that a Selection represents the user's selection, while Range represents a continuous part of a document independently of any visual representation. A Selection can (almost) be expressed in terms of zero, one or more Ranges but Ranges can also be created and modified completely independently of the selection.

There is some overlap in functionality: for example, Selection's deleteFromDocument() is equivalent to calling deleteContents() on all of its component Ranges, and you can get the boundaries of the most recently selected Range in the selection using the anchorNode, anchorOffset, focusNode and focusOffset properties. However, there are some crucial differences:

  • A Selection may contain multiple Ranges. However, the only major browser to support this currently is Firefox.
  • A Selection may be "backwards", by which I mean that the end boundary of the selection (represented by focusNode and focusOffset) may occur earlier in the document than the start boundary (anchorNode and anchorOffset). A Range has no direction.
  • toString() works differently. In most browsers (although notably not IE 9), calling toString() on a Selection object returns only the visible text that is selected, while calling toString() on a Range will return a concatenation of all text nodes within the range, including those within <script> elements and elements hidden via CSS.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文