visibilitychange

当其选项卡的内容变得可见或被隐藏时,会在文档上触发 visibilitychange (能见度更改) 事件。

概述

Interface
event
Bubbles

Yes

Cancelable

No

Target
Document
Default Action

None

使用说明

该事件不包括文档的更新的可见性状态,但是你可以从文档的 visibilityState 属性中获取该信息。

警告: 当 visibleStateState 属性的值转换为 hidden 时,Safari 不会按预期触发 visibilitychange;因此,在这种情况下,你还需要包含代码以侦听 pagehide 事件。

警告: 出于兼容性原因,请确保使用 document.addEventListener 而不是 window.addEventListener 来注册回调。Safari <14.0 仅支持前者。

属性

Property Type Description
target 只读 EventTarget The event target (the topmost target in the DOM tree).
type 只读 DOMString The type of event.
bubbles 只读 Boolean Whether the event normally bubbles or not.
cancelable 只读 Boolean Whether the event is cancellable or not.

例子

本示例在文档可见时开始播放音乐曲目,在文档不再可见时暂停音乐。

js

document.addEventListener("visibilitychange", function () {
  console.log(document.visibilityState);
});
document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === 'visible') {
    backgroundMusic.play();
  } else {
    backgroundMusic.pause();
  }
});

规范

Specification
HTML Standard
# event-visibilitychange
HTML Standard
# handler-onvisibilitychange

浏览器兼容性

BCD tables only load in the browser

相关链接