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/ja/web/api/window/getselection/index.html | 101 ++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 files/ja/web/api/window/getselection/index.html (limited to 'files/ja/web/api/window/getselection') diff --git a/files/ja/web/api/window/getselection/index.html b/files/ja/web/api/window/getselection/index.html new file mode 100644 index 0000000000..13b908a7e5 --- /dev/null +++ b/files/ja/web/api/window/getselection/index.html @@ -0,0 +1,101 @@ +--- +title: window.getSelection +slug: Web/API/Window/getSelection +tags: + - API + - DOM + - Method + - NeedsMobileBrowserCompatibility + - Reference + - Selection + - Selection API + - Window +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

概要

+ +

ユーザーが選択した文字列の範囲やキャレットの現在位置を示す {{domxref("Selection")}} オブジェクトを返します。

+ +

構文

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

+ +

A {{domxref("Selection")}} オブジェクト。

+ +

文字列へ型変換すると、空の文字列("")を追加するか {{domxref("Selection.toString()")}} を使って、選択された文字列を返します。

+ +

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // 以下、取得した選択文字列に対して何らかの処理を行う
+}
+ +

注記

+ +

Selection オブジェクトの文字列表現

+ +

JavaScript では、文字列が渡されることを前提としている関数 ({{ Domxref("window.alert()") }} や {{ Domxref("document.write()") }}) にオブジェクトが渡されると、そのオブジェクトの {{jsxref("Object.toString", "toString()")}} メソッドが呼び出され、その結果が関数へ渡されます。このため、実際はプロパティとメソッドを持つオブジェクトなのに、文字列であるかのように見えてしまいます。

+ +

上の例では、{{domxref("window.alert()")}} へ渡されるときに自動的に selObj.toString() が呼び出されます。しかし、{{domxref("Selection")}} オブジェクトで JavaScript の String プロパティや lengthsubstr などのメソッドを直に使おうとすると、オブジェクトにその名前のプロパティやメソッドが存在しないはエラーとなり、存在する場合は予期せぬ結果を返すでしょう。Selection オブジェクトを文字列として使うなら、下記のように toString() メソッドを呼び出してください。

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

同じように機能する {{domxref("Document.getSelection()")}} を呼び出すことができます。

+ +

HTML input 要素は selection を扱うための簡単な支援 API を提供しています。 (詳細: {{domxref("HTMLInputElement.setSelectionRange()")}})

+ +

selectionfocus の違いに注意してください。{{domxref("Document.activeElement")}} はフォーカスされた要素を返します。

+ +

仕様

+ + + + + + + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName("Selection API", "#extensions-to-window-interface", "Window.getSelection()")}}{{Spec2("Selection API")}}新仕様
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}初期定義
+ +

ブラウザー実装状況

+ + + +

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

+ +

関連情報

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