--- title: 'Window: focus event' slug: Web/API/Window/focus_event tags: - API - Event - Focus translation_of: Web/API/Window/focus_event ---
当元素获得焦点时, focus
事件就会触发。
与 focus
相反的事件是 {{domxref("Window/blur_event", "blur")}}
Bubbles(支持冒泡) | No |
---|---|
Cancelable(可撤销) | No |
Interface(接口) | {{DOMxRef("FocusEvent")}} |
Event handler property(事件处理程序属性) | {{domxref("GlobalEventHandlers/onfocus", "onfocus")}} |
Sync / Async(同步/异步) | Sync |
Composed(可组成) | Yes |
本示例在失去焦点时更改文档的外观。它使用 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 监听 focus
和 {{domxref("Window/blur_event", "blur")}} 事件。
<p id="log">Click on this document to give it focus.</p>
.paused { background: #ddd; color: #555; }
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);
{{EmbedLiveSample("Live_example")}}
规范 | 状态 | 备注 |
---|---|---|
{{SpecName("UI Events", "#event-type-focus")}} | {{Spec2("UI Events")}} | 添加了组成此事件的信息。 |
{{SpecName("DOM3 Events", "#event-type-focus")}} | {{Spec2("DOM3 Events")}} | 初始定义 |
{{Compat("api.Window.focus_event")}}
Element
目标上的这个事件: {{domxref("Element/focus_event", "focus")}} 事件