Skip to content

Commit 380fb26

Browse files
committed
监听浏览器标签页的显示与隐藏
1 parent 57fa95a commit 380fb26

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

Native-JavaScript/dom-handle.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// DOM 相关处理
2+
3+
/**
4+
* 监听浏览器标签页的显示与隐藏
5+
*/
6+
class ListenerPageVisibility {
7+
constructor () {
8+
// 设置隐藏属性和改变可见属性的事件的名称
9+
this.hidden = ''
10+
this.visibilityChange = ''
11+
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
12+
this.hidden = "hidden"
13+
this.visibilityChange = "visibilitychange"
14+
} else if (typeof document.msHidden !== "undefined") {
15+
this.hidden = "msHidden"
16+
this.visibilityChange = "msvisibilitychange"
17+
} else if (typeof document.webkitHidden !== "undefined") {
18+
this.hidden = "webkitHidden"
19+
this.visibilityChange = "webkitvisibilitychange"
20+
}
21+
22+
this.handleChange = (callBackHidden, callBackVisibility) => {
23+
if (document[this.hidden]) {
24+
// 页面是隐藏状态
25+
callBackHidden && callBackHidden()
26+
} else {
27+
// 页面是展示状态
28+
callBackVisibility && callBackVisibility()
29+
}
30+
}
31+
32+
}
33+
34+
/**
35+
* 全局访问点
36+
* @param callBackHidden 页面隐藏执行的回调方法
37+
* @param callBackVisibility 页面显示执行的回调方法
38+
*/
39+
linsternVisibility (callBackHidden, callBackVisibility) {
40+
// 如果浏览器不支持addEventListener 或 Page Visibility API 给出警告
41+
if (typeof document.addEventListener === "undefined" || typeof document[this.hidden] === "undefined") {
42+
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.")
43+
} else {
44+
// 处理页面可见属性的改变
45+
document.addEventListener(this.visibilityChange, () => {
46+
this.handleChange(callBackHidden, callBackVisibility)
47+
}, false)
48+
}
49+
}
50+
}
51+
52+
// 调用实例
53+
let navChange = new ListenerPageVisibility()
54+
navChange.linsternVisibility(
55+
// 页面是隐藏状态执行方法
56+
() => {
57+
// TODO 浏览器标签页处于隐藏状态时,执行的方法
58+
},
59+
// 页面是可见状态执行方法
60+
() => {
61+
// TODO 浏览器标签页处于显示状态时,执行的方法
62+
}
63+
)

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,17 @@
4747
- [深度比较两个对象是否相等](/Native-JavaScript/data-type-handle.js)
4848
</details>
4949

50+
* <details>
51+
<summary>DOM相关处理</summary>
52+
53+
- [监听浏览器标签页的显示与隐藏](/Native-JavaScript/dom-handle.js)
54+
</details>
55+
5056
* [滚动条处理](/Native-JavaScript/scroll-handle.js)
5157
* [获取url的参数值,兼容search和hash](/Native-JavaScript/url-param.js)
5258
* [原生ajax封装](/Native-JavaScript/ajax.js)
5359

60+
5461
> Vue 2
5562
* <details>
5663
<summary>Vue指令</summary>

0 commit comments

Comments
 (0)