这是 实验性技术
检查 浏览器兼容性表格 要小心谨慎在生产中使用这之前。

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
}
					

注意事项

String representation of the Selection object

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.
过时 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
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

图例

完整支持

完整支持

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

元数据

  • 最后修改: