30秒学会 JavaScript 片段 · 2022年12月6日

30秒学会 JavaScript 片段 – Get selected text

Gets the currently selected text.

  • Use Window.getSelection() and Selection.toString() to get the currently selected text.

代码实现

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'

翻译自:https://www.30secondsofcode.org/js/s/get-selected-text