Element:focus 事件

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

當元素獲得焦點時,會觸發 focus 事件。該事件不會冒泡,但緊隨其後的相關 focusin 事件會冒泡。

focus 事件的反向事件是 blur 事件,當元素失去焦點時會觸發該事件。

focus 事件是不可取消的。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("focus", (event) => { })

onfocus = (event) => { }

事件型別

一個 FocusEvent。繼承自 UIEventEvent

Event UIEvent FocusEvent

事件屬性

此介面還繼承了其父級 UIEvent 的屬性,以及間接繼承自 Event 的屬性。

FocusEvent.relatedTarget

失去焦點的元素(如果有)。

示例

簡單示例

HTML

html
<form id="form">
  <label>
    Some text:
    <input type="text" placeholder="text input" />
  </label>
  <label>
    Password:
    <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 = "";
});

結果

事件委託

有兩種方法可以實現此事件的事件委託:使用 focusin 事件,或將 addEventListener()useCapture 引數設定為 true

HTML

html
<form id="form">
  <label>
    Some text:
    <input type="text" placeholder="text input" />
  </label>
  <label>
    Password:
    <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,
);

結果

規範

規範
UI 事件
# event-type-focus
HTML
# handler-onfocus

瀏覽器相容性

另見