用jquery实现垂直左右居中


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>居中</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<style>
   
	 .center {
				background-color: #FFFF00;
				height: 200px;
				width: 300px;
              } 
	 
</style>
<body>
       <div id="box">
	         <div class="center"></div>
	   </div>
</body>
<script>
    $(function(json){
	      function  Fjuzhong(){
		        var win ={},middle={};//win为浏览器的长宽对象,middle为要居中的元素的长宽对象
				var objDom =$(json.obj); 
				    win.width = $(window).width();
					win.height = $(window).height();
					middle.width = objDom.width();
					middle.height = objDom.height();
			    var left=(win.width-middle.width)/2+"px";
				var top=(win.height-middle.height)/2+"px";
					objDom.css({"margin-top":top,"margin-left":left});
					
					$(window).resize(Fjuzhong);//当浏览器长宽发生变化时,元素会相应居中
			
		  }
		  var json = {"obj":".center"};
		  Fjuzhong(json);
	});
</script>
</html>

 

 

posted @ 2014-03-22 20:27  奋力向前CO  阅读(516)  评论(0编辑  收藏  举报