From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/window/getselection/index.html | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 files/zh-cn/web/api/window/getselection/index.html (limited to 'files/zh-cn/web/api/window/getselection') diff --git a/files/zh-cn/web/api/window/getselection/index.html b/files/zh-cn/web/api/window/getselection/index.html new file mode 100644 index 0000000000..6c2bebc684 --- /dev/null +++ b/files/zh-cn/web/api/window/getselection/index.html @@ -0,0 +1,82 @@ +--- +title: Window.getSelection +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +
+ +

返回一个 {{domxref("Selection")}} 对象,表示用户选择的文本范围或光标的当前位置。

+ +

语法

+ +
const selection = window.getSelection() ;
+ + + +

示例

+ +
function foo() {
+    let selObj = window.getSelection();
+    console.log(selObj);
+    let selRange = selObj.getRangeAt(0);
+    // 其他代码
+}
+ +

备注

+ +

在  JavaScript中,当一个对象被传递给期望字符串作为参数的函数中时(如 {{ Domxref("window.alert") }} 或 {{ Domxref("document.write") }}),对象的{{jsxref("Object.toString","toString()")}}方法会被调用,然后将返回值传给该函数。

+ +

在上例中,selObj.toString() 会在传递到 {{domxref("window.alert()")}}时自动调用。然而,当你试图在 {{domxref("Selection")}} 对象上使用一个 JavaScript 的{{jsxref("Global_Objects/String", "String")}} 对象上的属性或者方法时(如 {{jsxref("String.prototype.length")}} 或者 {{jsxref("String.prototype.substr()")}}),会导致错误(如果没有相应的属性或方法时)或返回不是期望的结果(如果存在相应的属性或方法)。如果想要将 Selection 对象作为一个字符串使用,请直接调用 toString() 方法:

+ +
var selectedText = selObj.toString();
+ + + +

相关对象

+ + + +

你还可以使用 {{domxref("Document.getSelection()")}},两个方法等价。

+ +

值得注意的是,目前在Firefox, Edge (非 Chromium 版本) 及 Internet Explorer 中,getSelection() 对 {{htmlelement("textarea")}} 及 {{htmlelement("input")}} 元素不起作用。 {{domxref("HTMLInputElement.setSelectionRange()")}} 或 selectionStart 及 selectionEnd 属性可用于解决此问题。

+ +

还要注意选择不同于焦点(详见 Selection 及输入焦点)。可使用{{domxref("Document.activeElement")}} 来返回当前的焦点元素.

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.getSelection")}}

+ +

相关链接

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
-- cgit v1.2.3-54-g00ecf