Document: visibilitychange event - Web APIs 编辑
The visibilitychange
event is fired at the document when the content of its tab have become visible or have been hidden.
Bubbles | Yes |
---|---|
Cancelable | No |
Interface | Event |
Event handler property | onvisibilitychange |
Usage notes
The event doesn't include the document's updated visibility status, but you can get that information from the document's visibilityState
property.
Safari doesn’t fire visibilitychange
as expected when the value of the visibilityState
property transitions to hidden
; so for that case, you need to also include code to listen for the pagehide
event.
For compatibility reasons, make sure to use document.addEventListener
to register the callback and not window.addEventListener
. Safari < 14.0 only supports the former.
Examples
This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible.
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === 'visible') {
backgroundMusic.play();
} else {
backgroundMusic.pause();
}
});
Specifications
Specification | Status | Comment |
---|---|---|
Page Visibility (Second Edition) The definition of 'visibilitychange' in that specification. | Recommendation |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论