这是
实验性技术
检查
浏览器兼容性表格
要小心谨慎在生产中使用这之前。
getSelection()
特性为
DocumentOrShadowRoot
interface returns a
Selection
对象,表示用户选择的文本范围或 ^ 插入符号的当前位置。
var selection = documentOrShadowRootInstance.getSelection()
None.
A
Selection
对象。
function foo() {
var selObj = document.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
// do stuff with the range
}
In JavaScript, when an object is passed to a function expecting a string (like
Window.alert()
), the object's
toString()
method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods.
In the above example,
selObj.toString()
is automatically called when it is passed to
Window.alert()
. However, attempting to use a JavaScript
字符串
property or method such as
length
or
substr
directly on a
Selection
object results in an error if it does not have that property or method and may return unexpected results if it does. To use a
Selection
object as a string, call its
toString()
method directly:
var selectedText = selObj.toString();
selObj
是
Selection
对象。
selectedText
is a string (Selected text).
可以调用
Window.getSelection()
, which works identically to
Document.getSelection()
.
It is worth noting that currently
getSelection()
doesn't work on the content of
<input>
elements in Firefox.
HTMLInputElement.setSelectionRange()
) could be used to work around this.
Notice also the difference between
selection
and
focus
.
Document.activeElement
returns the focused element.
| 规范 | 状态 | 注释 |
|---|---|---|
|
Shadow DOM
The definition of 'DocumentOrShadowRoot' in that specification. |
过时 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getSelection
|
Chrome 53 | Edge 12 | Firefox 63 | IE Yes | Opera 40 | Safari Yes | WebView Android 53 | Chrome Android 53 | Firefox Android 63 | Opera Android 41 | Safari iOS Yes | Samsung Internet Android 6.0 |
完整支持
实验。期望将来行为有所改变。
DocumentOrShadowRoot
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument