元素:focus 事件

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

focus 事件在元素获取焦点时触发。这个事件和 focusin 最大的区别仅仅在于后者会事件冒泡。

focusblur 正好相反。

该事件不可取消,也不会冒泡。

语法

在象 addEventListener() 这样的方法中使用事件名称或设置事件处理器属性。

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

onfocus = (event) => {};

事件属性

该接口还从其父级 UIEventEvent 继承属性。

FocusEvent.relatedTarget

一个 EventTarget,表示此事件的次要目标。在某些情况下(例如切换到当前标签页或离开当前标签页),处于安全原因,该属性可能会被设置为 null

示例

简单示例

HTML

html
<form id="form">
  <input type="text" placeholder="text input" />
  <input type="password" placeholder="password" />
</form>

结果

事件委托

此事件有两个可以实现事件委托的方法:通过在支持的浏览器上使用 focusin 事件,或者通过设置 addEventListener() 的参数useCapture 值为 true

HTML

html
<form id="form">
  <input type="text" placeholder="text input" />
  <input type="password" placeholder="password" />
</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

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
focus event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见