前台验证是否是PC端访问

在jsp中,有时需要判断是PC端还是手机端,并对组件进行分别处理。例如下面的例子:

<script type="text/javascript">
	function IsPC() { 
		var userAgentInfo = navigator.userAgent; 
		var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"); 
		var flag = true; 
		for (var v = 0; v < Agents.length; v++) { 
			if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } 
		}
		return flag;
	}
	function init() {
		if (IsPC()) {
			document.getElementById("index").style.width="560px";
			// document.all.index.offsetWidth中的"index"是div组件的id
			var leftValue = (document.body.offsetWidth - document.all.index.offsetWidth) / 2;
			alert(leftValue);
			document.getElementById("index").style.left = leftValue + "px";
		}
		var submitFlag = document.getElementById("submitFlag").value;
		if ("1" == submitFlag) {
			document.getElementById("submitFlag").value = "0";
			window.location.reload();
		}
	}
	window.onresize=function(){
		if (IsPC()) {
	        changeDivHeight();  
		}
   	};
   	function changeDivHeight(){               
       var w = document.documentElement.clientWidth;//获取页面可见宽度 
       var leftValue = (w - document.all.index.offsetWidth) / 2;
       document.getElementById("index").style.left = leftValue + "px";
	}
</script>


<div id="index" style="position:absolute;margin-left:auto;margin-right: auto;">
……
</div>


该例子用于判断是否是PC端访问页面,是PC端则控制指定div居中显示。并且在浏览器窗口变化时进行div自适应。

你可能感兴趣的:(div水平居中,判断是否是PC端,浏览器窗口大小改变事件,div宽度自适应)