元素: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.
语法
在象 addEventListener()
这样的方法中使用事件名称或设置事件处理器属性。
js
addEventListener("focus", (event) => {});
onfocus = (event) => {};
事件属性
该接口还从其父级 UIEvent
和 Event
继承属性。
-
一个
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 GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
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.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
参见
- 相关的事件:
blur
、focusin
、focusout
- 在
Window
目标上的该事件:focus
事件 - Focusing: focus/blur