このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
HTMLTextAreaElement: selectionchange イベント
Baseline 2024Newly available
Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
selectionchange は選択 API のイベントで、<textarea> 要素内のテキストの選択状態が変更されたときに発生します。これは、文字の選択範囲の変更と、キャレットが移動した場合の両方を含みます。
このイベントはキャンセル不可です。
イベントは通常<textarea> にイベントリスナーを追加することで処理され、HTMLTextAreaElement で読み込まれるハンドラー関数で処理されます。selectionStart、selectionEnd、selectionDirection プロパティで読み取ります。
グローバルなonselectionchange イベントハンドラーにリスナーを追加し、ハンドラー関数内でDocument.getSelection() を使用してSelection を取得することも可能です。しかし、これはテキスト の選択範囲の変更を取得するのにはあまり有益ではありません。
In this article
構文
このイベント名をaddEventListener() などのメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。
addEventListener("selectionchange", (event) => { })onselectionchange = (event) => { }イベント型
一般的なEvent です。
例
下記の例では、<textarea> 要素内での選択範囲を取得する方法を紹介します。
HTML
<div> ここにテキストを入力して選択してください:<br /><textarea rows="2" cols="20"></textarea></div><div>selectionStart: <span></span></div><div>selectionEnd: <span></span></div><div>selectionDirection: <span></span></div>JavaScript
const myInput = document.getElementById("my-text");myInput.addEventListener("selectionchange", () => { document.getElementById("start").textContent = myInput.selectionStart; document.getElementById("end").textContent = myInput.selectionEnd; document.getElementById("direction").textContent = myInput.selectionDirection;});例
仕様書
| Specification |
|---|
| Selection API> # selectionchange-event> |
| Selection API> # dom-globaleventhandlers-onselectionchange> |