星空网 > 软件开发 > Java

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

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='/images/loading.gif' data-original="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='/images/loading.gif' data-original="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设置为水平垂直居中

关键词:jquery

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

The Hello Smile:https://www.ikjzd.com/w/4450
Art Of Techno:https://www.ikjzd.com/w/4451
fabritones:https://www.ikjzd.com/w/4452
icancycling:https://www.ikjzd.com/w/4453
优量汇:https://www.ikjzd.com/w/4455
睿超科技(RECO):https://www.ikjzd.com/w/4456
桂林酒店销售多少钱 桂林旅游宾馆价格:https://www.vstour.cn/a/410227.html
十里银滩旅游攻略玩什么住哪里怎么去?:https://www.vstour.cn/a/410228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流