{}); onfocus = (event) => {}; 事件属性 该">

语法

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

jsaddEventListener("focus", (event) => {});

onfocus = (event) => {};

事件属性

该接口还从其父级 UIEvent 和 Event 继承属性。

FocusEvent.relatedTarget

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

示例

简单示例

HTML

html

结果

事件委托

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

HTML

html

JavaScript

jsconst 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

浏览器兼容性

Loading…

参见

相关的事件:blur、focusin、focusout

在 Window 目标上的该事件:focus 事件

Focusing: focus/blur

Help improve MDN

Was this page helpful to you?

Yes

No

Learn how to contribute

This page was last modified on ⁨2024年6月6日⁩ by MDN contributors.

View this page on GitHub • Report a problem with this content


轻松解除银行卡绑定,微信支付更顺手!
如何设置QQ多彩气泡