--- title: visibilitychange slug: Web/API/Document/visibilitychange_event tags: - API - Visibility - visibilitychange translation_of: Web/API/Document/visibilitychange_event ---
{{APIRef}}
当其选项卡的内容变得可见或被隐藏时,会在文档上触发 visibilitychange (能见度更改)事件。
该事件不包括文档的更新的可见性状态,但是您可以从文档的 {{domxref("Document.visibilityState", "visibilityState")}} 属性中获取该信息。
当 visibleStateState 属性的值转换为 hidden 时,Safari不会按预期触发visibilitychange; 因此,在这种情况下,您还需要包含代码以侦听 pagehide 事件。
出于兼容性原因,请确保使用 document.addEventListener 而不是window.addEventListener来注册回调。 Safari <14.0仅支持前者。
| Property | Type | Description |
|---|---|---|
target {{readonlyInline}} |
{{domxref("EventTarget")}} | The event target (the topmost target in the DOM tree). |
type {{readonlyInline}} |
{{domxref("DOMString")}} | The type of event. |
bubbles {{readonlyInline}} |
{{jsxref("Boolean")}} | Whether the event normally bubbles or not. |
cancelable {{readonlyInline}} |
{{jsxref("Boolean")}} | Whether the event is cancellable or not. |
本示例在文档可见时开始播放音乐曲目,在文档不再可见时暂停音乐。
document.addEventListener("visibilitychange", function() {
console.log( document.visibilityState );
});
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === 'visible') {
backgroundMusic.play();
} else {
backgroundMusic.pause();
}
});
| 规范 | 状态 | 注释 |
|---|---|---|
| W3C Page Visibility API | {{Spec2('Page Visibility API')}} |
{{Compat("api.Document.visibilitychange")}}
{{Compat("api.Document.visibilitychange_event")}}