码迷,mamicode.com
首页 > Web开发 > 详细

jQuery如何将div设置为水平垂直居中

时间:2015-07-09 21:25:11      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

jQuery如何将div设置为水平垂直居中:
使用CSS也可以实现div的水平垂直居中效果,但是有时候可能需要动态的调整,下面就介绍一下如何用jQuery实现对象的水平垂直居中效果,先看一段代码实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css"> 
.mytest{ 
  width:200px; 
  height:100px; 
  background-color:green; 
} 
</style> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
  $(window).resize(function(){ 
    $(".mytest").css({ 
      position:absolute, 
      left:($(window).width() - $(".mytest").outerWidth())/2, 
      top:($(window).height() - $(".mytest").outerHeight())/2 + $(document).scrollTop() 
    }); 
  }); 
  $(window).resize();    
}) 
</script> 
</head> 
<body> 
  <div class="mytest"></div> 
</body> 
</html>

以上代码实现了将div在窗口中水平垂直居中效果,无论是否调整窗口大小。可能有些朋友会说,这个是在窗口中垂直居中的,如何实现一个div在一个普通的福对象中垂直居中,代码修改如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css"> 
.parent{ 
  width:500px; 
  height:500px; 
  background-color:red; 
} 
.children{ 
  width:200px; 
  height:100px; 
  background-color:green; 
} 
</style> 
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
  $(window).resize(function(){ 
    $(".children").css({ 
      position:absolute, 
      left:($(".parent").width() - $(".children").outerWidth())/2, 
      top:($(".parent").height() - $(".children").outerHeight())/2 + $(document).scrollTop() 
    }); 
  }); 
  $(window).resize();    
}) 
</script> 
</head> 
<body> 
<div class="parent"> 
  <div class="children"></div> 
</div>  
</body> 
</html>

以上代码实现了字div在父div中的水平垂直居中效果。

原文地址是:http://www.51texiao.cn/jqueryjiaocheng/2015/0427/244.html

jQuery如何将div设置为水平垂直居中

标签:

原文地址:http://www.cnblogs.com/nulifendou/p/4634123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!