Element: focus イベント
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
focus イベントは、要素がフォーカスを受け取ったときに発生します。このイベントはバブリングしませんが、その後に発生する関連する focusin イベントはバブリングします。
focus の反対は blur であり、これは要素がフォーカスを失ったときに発生します。
focus イベントはキャンセル不可です。
構文
このイベント名を addEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。
js
addEventListener("focus", (event) => {});
onfocus = (event) => {};
イベント型
FocusEvent です。 Event を継承しています。
イベントプロパティ
親である UIEvent および間接的に Event から継承したプロパティもあります。
-
もしあれば、フォーカスを受け取った要素。
例
>簡単な例
HTML
html
<form id="form">
<label>
テキストを入力:
<input type="text" placeholder="テキストを入力" />
</label>
<label>
パスワード:
<input type="password" placeholder="password" />
</label>
</form>
JavaScript
js
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 つあります。 focusin イベントを使用するか、 addEventListener() の useCapture 引数に true を設定するかです。
HTML
html
<form id="form">
<label>
テキストを入力:
<input type="text" placeholder="テキストを入力" />
</label>
<label>
パスワード:
<input type="password" placeholder="password" />
</label>
</form>
JavaScript
js
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-focus> |
| HTML> # handler-onfocus> |
ブラウザーの互換性
Loading…
関連情報
HTMLElement.focus()メソッド- 関連イベント:
blur,focusin,focusout Windowを対象としたこのイベント:focusイベント- Focusing: focus/blur