<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="" content=""> <title></title> <style> </style> </head> <body> <p>ok</p> <script>
// 第一种: // var hiddenProperty = ‘hidden‘ in document ? ‘hidden‘ : // ‘webkitHidden‘ in document ? ‘webkitHidden‘ : // ‘mozHidden‘ in document ? ‘mozHidden‘ : // null; // var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, ‘visibilitychange‘); // var onVisibilityChange = function(){ // if (!document[hiddenProperty]) { // console.log(‘页面激活‘); // }else{ // console.log(‘页面非激活‘) // } // } // document.addEventListener(visibilityChangeEvent, onVisibilityChange);
//第二种:
document.addEventListener("visibilitychange", function() { console.log(document.visibilityState); if(document.visibilityState == "hidden") { console.log(‘隐藏‘); } else if (document.visibilityState === "visible") { console.log(‘显示‘) } }); </script> </body> </html>