このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
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 イベントはキャンセル不可です。
In this article
構文
このイベント名をaddEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。
js
addEventListener("focus", (event) => {});onfocus = (event) => {};イベント型
FocusEvent です。Event を継承しています。
イベントプロパティ
親であるUIEvent および間接的にEvent から継承したプロパティもあります。
FocusEvent.relatedTargetもしあれば、フォーカスを受け取った要素。
例
>簡単な例
HTML
html
<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> <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> |
ブラウザーの互換性
関連情報
HTMLElement.focus()メソッド- 関連イベント:
blur,focusin,focusout Windowを対象としたこのイベント:focusイベント- Focusing: focus/blur