このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

HTMLInputElement: selectionchange イベント

Baseline 2024
Newly available

Since ⁨September 2024⁩, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。

selectionchange選択 API のイベントで、 <input> 要素の中でテキストの選択状態が変化したときに発行されます。 これは、文字単位の選択範囲位が変化した場合も、キャレットが移動したときも含みます。

このイベントはキャンセル不可です。

このイベントは通常 <input> 上にイベントリスナーを追加し、ハンドラー関数内で HTMLInputElementselectionStartselectionEndselectionDirection の各プロパティを読み取ることで処理します。

また、onselectionchange イベントハンドラーにリスナーを追加し、ハンドラー関数内で Document.getSelection() を使って選択状態を得ることもできます。しかし、これはテキストの選択範囲の変更を取得するのにはあまり便利ではありません。

構文

このイベント名を addEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("selectionchange", (event) => {}); onselectionchange = (event) => {}; 

イベント型

一般的な Event です。

以下の例は、 <input> 要素の中にあるテキストの選択状態を取得する方法を示しています。

HTML

html
<div> こちらにテキストを入力して選択してください:<br /><input id="mytext" rows="2" cols="20" /> </div> <div>selectionStart: <span id="start"></span></div> <div>selectionEnd: <span id="end"></span></div> <div>selectionDirection: <span id="direction"></span></div> 

JavaScript

js
const myinput = document.getElementById("mytext"); 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

ブラウザーの互換性