Window: focus event

当元素获得焦点时, focus 事件就会触发。

与 focus 相反的事件是 blur

Bubbles(支持冒泡) No
Cancelable(可撤销) No
Interface(接口) FocusEvent
Event handler property(事件处理程序属性) onfocus
Sync / Async(同步/异步) Sync
Composed(可组成) Yes

示例

在线示例

本示例在失去焦点时更改文档的外观。它使用 addEventListener() 监听 focusblur 事件。

HTML

<p id="log">Click on this document to give it focus.</p>

CSS

.paused {
  background: #ddd;
  color: #555;
}

JavaScript

function pause() {
  document.body.classList.add('paused');
  log.textContent = 'FOCUS LOST!';
}

function play() {
  document.body.classList.remove('paused');
  log.textContent = 'This document has focus. Click outside the document to lose focus.';
}

const log = document.getElementById('log');

window.addEventListener('blur', pause);
window.addEventListener('focus', play);

结果

规范

规范 状态 备注
UI Events Working Draft 添加了组成此事件的信息。
Document Object Model (DOM) Level 3 Events Specification Obsolete 初始定义

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
focus eventChrome Full support YesEdge Full support 12Firefox Full support Yes
Full support Yes
No support ? — 24
Notes
Notes The interface for this event is Event, not FocusEvent.
IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
See implementation notes.
See implementation notes.

参考

  • 相关联事件: blur
  • Element 目标上的这个事件: focus 事件