元素:blur 事件

Baseline 已廣泛支援

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

當一個元素失去焦點時,會觸發 blur 事件。該事件不會冒泡,但隨後會觸發相關的 focusout 事件,該事件會冒泡。

當另一個元素被選中時,元素會失去焦點。當應用於元素的樣式不允許獲得焦點(例如 hidden)或元素從文件中移除時,元素也會失去焦點——在這兩種情況下,焦點都會移至 body 元素(視口)。但請注意,當獲得焦點的元素從文件中移除時,不會觸發 blur

blur 事件相反的是 focus 事件,當元素獲得焦點時會觸發此事件。

blur 事件是不可取消的。

語法

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

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

onblur = (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 = "";
});

結果

事件委託

有兩種方法可以實現此事件的事件委託:使用 focusout 事件,或將 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-blur
HTML
# handler-onblur

瀏覽器相容性

在處理此事件時,Document.activeElement 的值在不同瀏覽器中有所不同(Firefox bug 452307):IE10 將其設定為焦點將要移到的元素,而 Firefox 和 Chrome 通常將其設定為文件的 body

另見