Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. Element
  4. 元素:focus 事件

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

View in EnglishAlways switch to English

元素:focus 事件

Baseline Widely available

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

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

focusblur 正好相反。

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

语法

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

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

事件属性

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

FocusEvent.relatedTarget

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

示例

简单示例

HTML

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

结果

事件委托

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

HTML

html
<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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp