Selection API - Web APIs 编辑
The Selection API provides functionality for reading and manipulating the range of text selected by the user.
Concepts and usage
To retrieve the current text range the user has selected, you can use the Window.getSelection()
or Document.getSelection()
method, storing the return value — a Selection
object — in a variable for futher use.
Once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using Selection.toString()
, adding a range (as represented by a standard Range
object) to the selection (or removing one) with Selection.addRange()
/Selection.removeRange()
, or changing the selection to be the entire contents of a DOM node using Selection.selectAllChildren()
.
You can run code in response to the selection being changed, or a new selection being started, using the GlobalEventHandlers.onselectionchange
and GlobalEventHandlers.onselectstart
event handlers.
Selection API interfaces
Selection
- Represents the range of text selected by the user or the current position of the caret.
Extensions to other interfaces
Window.getSelection()
,Document.getSelection()
- Returns a
Selection
object representing the range of text selected by the user or the current position of the caret.Document.getSelection()
is basically an alias ofWindow.getSelection()
. GlobalEventHandlers.onselectstart
- Represents the event handler that is called when a
selectstart
event is fired on the current object (i.e. when a new range of text is about to be selected by the user). GlobalEventHandlers.onselectionchange
- Represents the event handler that is called when a
selectionchange
event is fired on the current object (i.e. when the selected text range changes).
Specifications
Specification | Status | Comment |
---|---|---|
Selection API The definition of 'Selection' in that specification. | Working Draft | The Selection API specification is based on the HTML Editing APIs specification and focuses on the Selection-related functionality. |
HTML Editing APIs The definition of 'Selection' in that specification. | Editor's Draft | Initial (older) definition, which is now outdated. |
Browser compatibility
Selection
BCD tables only load in the browser
See also
- Key quote generator: A simple demo showing typical usage of the Selection API to capture the current selection at any point and copy selections into a list (see it live also).
- The
Range
object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论