文档:getSelection() 方法

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本中正常工作。自 ⁨2017 年 11 月⁩ 以来,所有浏览器均已支持此功能。

Document 接口的 getSelection() 方法会返回与该文档关联的 Selection 对象,该对象表示用户选择的文本范围,或者光标的当前位置。

语法

js
getSelection()

参数

无。

返回值

一个 Selection 对象,或者在文档没有 浏览上下文 的情况下返回 null(例如,它是未附加到文档的 <iframe> 的文档)。

示例

获取 Selection 对象

js
const selection = document.getSelection();
const selRange = selection.getRangeAt(0);
// do stuff with the range

console.log(selection); // Selection object

Selection 对象的字符串表示形式

某些函数(例如 Window.alert())会自动调用 toString(),并会将返回值传递给函数。因此,这将返回选定的文本,而不是 Selection 对象。

js
alert(selection);

但是,并非所有函数都会自动调用 toString()。要将 Selection 对象用作字符串,请直接调用其 toString() 方法。

js
let selectedText = selection.toString();

您可以调用 Window.getSelection(),这与 window.document.getSelection() 相同。

值得注意的是,目前 getSelection() 在 Firefox 中对 <input> 元素的 **内容** 不起作用。可以使用 HTMLInputElement.setSelectionRange() 来解决此问题。

同时也要注意“选择”和“焦点”之间的区别。Document.activeElement 会返回当前获得焦点的元素。

规范

规范
Selection API
# dom-document-getselection

浏览器兼容性