Movatterモバイル変換


[0]ホーム

URL:


  1. 開発者向けのウェブ技術
  2. Web API
  3. Element
  4. focus

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

View in EnglishAlways switch to English

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 を継承しています。

Event UIEvent FocusEvent

イベントプロパティ

親である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

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp