此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Element:focus 事件

基线
广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

focus 事件在元素获得焦点时触发。此事件不会冒泡,但随后触发的相关 focusin 事件会冒泡。

与 focus 相反的是 blur 事件,该事件在元素失去焦点时触发。

focus 事件不可取消。

语法

在 addEventListener() 等方法中使用事件名称,或设置事件处理器属性。

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

onfocus = (event) => { }

事件类型

FocusEvent。继承自 UIEvent 和 Event。

Event UIEvent FocusEvent

示例

简单示例

HTML

html
<form id="form">
  <label>一些文本:<input type="text" placeholder="文本输入" /></label>
  <label>密码:<input type="password" placeholder="密码" /></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>一些文本:<input type="text" placeholder="文本输入" /></label>
  <label>密码:<input type="password" placeholder="密码" /></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 Events
# event-type-focus
HTML
# handler-onfocus

浏览器兼容性

参见