From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../api/document/visibilitychange_event/index.html | 124 +++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 files/zh-cn/web/api/document/visibilitychange_event/index.html (limited to 'files/zh-cn/web/api/document/visibilitychange_event') diff --git a/files/zh-cn/web/api/document/visibilitychange_event/index.html b/files/zh-cn/web/api/document/visibilitychange_event/index.html new file mode 100644 index 0000000000..f1c945c5ea --- /dev/null +++ b/files/zh-cn/web/api/document/visibilitychange_event/index.html @@ -0,0 +1,124 @@ +--- +title: visibilitychange +slug: Web/API/Document/visibilitychange_event +tags: + - API + - Visibility + - visibilitychange +translation_of: Web/API/Document/visibilitychange_event +--- +

{{APIRef}}

+ +

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

+ +

概述

+ +
+
Specification
+
{{SpecName("Page Visibility API")}}
+
Interface
+
{{domxref("event")}}
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Target
+
{{domxref("Document")}}
+
Default Action
+
None
+
+ +

使用说明

+ +

该事件不包括文档的更新的可见性状态,但是您可以从文档的  {{domxref("Document.visibilityState", "visibilityState")}} 属性中获取该信息。

+ +
+

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

+
+ +
+

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

+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
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")}}

+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf