页面可见性事件

Posted 怪你无可取代

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了页面可见性事件相关的知识,希望对你有一定的参考价值。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Visibility API(兼容各种浏览器)</title>
</head>

<body onload="load()">
     <audio id="audio_id">
        <source src="always.mp3"/>
        <source src="demo-audio.ogg"/>
           Browser can‘t support Audio tag.
    </audio>
    <p>参考网址:https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API</p>

<script>
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}
 
var videoElement = document.getElementById("audio_id");

// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
  if (document[hidden]) {
    videoElement.pause();
  } else {
    videoElement.play();
  }
}

// Warn if the browser doesn‘t support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
  // Handle page visibility change   
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
    
  // When the video pauses, set the title.
  // This shows the paused
  videoElement.addEventListener("pause", function(){
    document.title = ‘Paused‘;
  }, false);
    
  // When the video plays, set the title.
  videoElement.addEventListener("play", function(){
    document.title = ‘Playing‘;
  }, false);

}
</script>
</body>
</html>

以上是关于页面可见性事件的主要内容,如果未能解决你的问题,请参考以下文章

从子用户控制页面设置父页面控制可见性

页面可见性改变事件 : visibilitychange 详解

Chrome 扩展:如何禁用页面可见性 API

页面可见性 API 是不是在脚本中的任何其他内容之前运行

如何在页面加载时在反应打字稿中设置可见性

循环访问 MS Access 子窗体并获取列可见性