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

浏览器兼容性

另见