about selection and range
The fundamental difference is that a Selection represents the user's selection, while Rangerepresents a continuous part of a document independently of any visual representation. ASelection 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
Selectionmay contain multiple Ranges. However, the only major browser to support this currently is Firefox. - A
Selectionmay be "backwards", by which I mean that the end boundary of the selection (represented byfocusNodeandfocusOffset) may occur earlier in the document than the start boundary (anchorNodeandanchorOffset). A Range has no direction. toString()works differently. In most browsers (although notably not IE 9), callingtoString()on aSelectionobject 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.
浙公网安备 33010602011771号