Element:focus 事件
当元素获得焦点时,会触发 focus 事件。该事件不会冒泡,但紧随其后的相关 focusin 事件会冒泡。
focus 事件的反向事件是 blur 事件,当元素失去焦点时会触发该事件。
focus 事件是不可取消的。
语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("focus", (event) => { })
onfocus = (event) => { }
事件类型
一个 FocusEvent。继承自 UIEvent 和 Event。
事件属性
此接口还继承了其父级 UIEvent 的属性,以及间接继承自 Event 的属性。
-
失去焦点的元素(如果有)。
示例
简单示例
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 |
浏览器兼容性
加载中…
另见
HTMLElement.focus()方法- 相关事件:
blur、focusin、focusout - 此事件在
Window上的目标:focus事件 - 聚焦:focus/blur