HTMLElement: beforeinput イベント
DOM の beforeinput
イベントは、<input>
、<select>
、<textarea>
要素の値が変更されようとしているときに発生します。 このイベントは、contenteditable
が有効になっている要素、および designMode
がオンになっている要素にも適用されます。
これにより、ブラウザーが DOM ツリーを変更する前に、ウェブアプリケーションがテキスト編集の動作を上書きすることができ、入力イベントをより詳細に制御してパフォーマンスを向上させることができます。
contenteditable
や designMode
の場合、イベントのターゲットは編集ホストです。これらのプロパティが複数の要素に適用された場合、編集ホストは、親が編集可能ではない直近の先祖要素になります。
バブリング | あり |
---|---|
キャンセル | 可 |
インターフェイス | InputEvent |
イベントハンドラープロパティ | なし |
同期 / 非同期 | 同期 |
Composed | はい |
既定のアクション | DOM 要素の更新 |
例
機能の検出
以下の関数は、 beforeinput
に対応していれば true を返します。
function isBeforeInputEventAvailable() {
return window.InputEvent && typeof InputEvent.prototype.getTargetRanges === "function";
}
単純なロガー
この例では、 <input>
要素に適用された新しい値に置き換える直前に、要素の現在の値をログに記録します。
HTML
<input placeholder="テキストを入力" name="name"/>
<p id="values"></p>
JavaScript
const input = document.querySelector('input');
const log = document.getElementById('values');
input.addEventListener('beforeinput', updateValue);
function updateValue(e) {
log.textContent = e.target.value;
}
結果
仕様書
Specification |
---|
UI Events # event-type-beforeinput |
ブラウザーの互換性
BCD tables only load in the browser
関連情報
- 関連イベント:
input