浏览器的visibilitychange 事件ie10以下不兼容
方法1,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="http://mat1.gtimg.com/www/js/jquery/jquery-1.11.1.min.js"></script> <script> /*** 切换浏览器tab,判断当前tab是否活跃 ***/ (function(g, h, $, b) { var e, i, f = 'onfocusin' in h && 'hasFocus' in h ? 'focusin focusout' : 'focus blur', d = ['', 'moz', 'ms', 'o', 'webkit'], c = $.support, a = $.event; while ((i = e = d.pop()) != b) { i = (e ? e + 'H' : 'h') + 'idden'; if (c.pageVisibility = typeof h[i] == 'boolean') { f = e + 'visibilitychange'; break } } $(/blur$/.test(f) ? g : h).bind(f, function(m) { var l = m.type, j = m.originalEvent, k = j.toElement; if (!/^focus./.test(l) || (k == b && j.fromElement == b && j.relatedTarget == b)) { a.trigger((i && h[i] || /^(?:blur|focusout)$/.test(l) ? 'hide' : 'show') + '.visibility') } }) }(this, document, jQuery)); var o={} o.$tabFlag = true; /** 切换页卡 **/ var changeTab=function() { console.log(333) $(document).bind({ 'show.visibility': function() { // 当前活跃 o.$tabFlag = true; console.log(222) }, 'hide.visibility': function() { // 失去当前状态 o.$tabFlag = false; console.log(11111) } }); } changeTab(); </script> </head> <body> </body> </html>
方法2
var o={}; // 找到当前浏览器支持的hidden属性名和visibilitychange事件名 var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.mozHidden !== "undefined") { hidden = "mozHidden"; visibilityChange = "mozvisibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } $(document).bind(visibilityChange,function(){ if (document[hidden]) { console.log(1111) o.$tabFlag = false; // videoElement.pause(); } else { console.log(222) o.$tabFlag = true; // videoElement.play(); } })
Feature | Chrome (Webkit) | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 13 webkit | 10 (10) moz 18 (18) |
10 ms | 12.10[*] | Not supported |
cssfirefly
http://cssfirefly.cnblogs.com