javascript检测浏览器是否在激活(可视)状态

直接上代码, 需要的复制走

<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<style>
table, th, td{font-size:12px; border:1px solid gray; border-collapse:collapse;}
</style>
<title>likelys.com</title>
<body>
<script>
		function bind(obj, type, fn){
			if(!obj){return false;}
			if(obj.attachEvent){
				obj.attachEvent('on'+type, function(){fn(window.event)});
			}else{
				obj.addEventListener(type, fn, false);
			}
		}
		
		
		// 设置隐藏属性和可见改变事件的名称,属性需要加浏览器前缀
		var hidden, state, visibilityChange, pageStatus = true;
		if (typeof document.hidden !== "undefined") {
			hidden = "hidden";
			visibilityChange = "visibilitychange";
			state = "visibilityState";
		} else if (typeof document.mozHidden !== "undefined") {
			hidden = "mozHidden";
			visibilityChange = "mozvisibilitychange";
			state = "mozVisibilityState";
		} else if (typeof document.msHidden !== "undefined") {
			hidden = "msHidden";
			visibilityChange = "msvisibilitychange";
			state = "msVisibilityState";
		} else if (typeof document.webkitHidden !== "undefined") {
			hidden = "webkitHidden";
			visibilityChange = "webkitvisibilitychange";
			state = "webkitVisibilityState";
		}


		bind(document, visibilityChange, function(e) {
			// 开始或停止状态处理
			if(document[state] == 'visible'){
				alert('visible');
				console.log('visible');
			}else if(document[state] == 'hidden'){
				alert('hide');
				console.log('hide');
			}
		});

</script>

</body>
</html>


本文链接:http://likelys.com/article/10531 posted @ 2015-09-18 12:49:47
top