文件: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

瀏覽器相容性