Element: blur イベント
blur
イベントは、要素がフォーカスを失ったときに発生します。このイベントと focusout
との違いは、 focusout
がバブリングするのに対し、 blur
はしないことです。
blur
の反対は focus
です。
バブリング | なし |
---|---|
キャンセル | 不可 |
インターフェイス | FocusEvent |
イベントハンドラープロパティ | onblur |
同期 / 非同期 | 同期 |
Composed | はい |
例
簡単な例
HTML
<form id="form">
<input type="text" placeholder="text input">
<input type="password" placeholder="password">
</form>
JavaScript
const password = document.querySelector('input[type="password"]');
password.addEventListener('focus', (event) => {
event.target.style.background = 'pink';
});
password.addEventListener('blur', (event) => {
event.target.style.background = '';
});
結果
イベント委譲
このイベントのイベント委譲を実装する方法は 2 つあります。 focusout
イベントを使用するか、 addEventListener()
の useCapture
引数に true
を設定するかです。
HTML
<form id="form">
<input type="text" placeholder="text input">
<input type="password" placeholder="password">
</form>
JavaScript
const form = document.getElementById('form');
form.addEventListener('focus', (event) => {
event.target.style.background = 'pink';
}, true);
form.addEventListener('blur', (event) => {
event.target.style.background = '';
}, true);
結果
仕様書
Specification |
---|
UI Events # event-type-blur |
HTML Standard # handler-onblur |
ブラウザーの互換性
BCD tables only load in the browser
このイベントが処理されている間、 Document.activeElement
の値はブラウザーによって異なります (Firefox バグ 452307)。 IE10 はフォーカスが移動する先の要素を設定しますが、 Firefox と Chrome ではふつう、文書の body
を設定します。