jQuery怎么将div设置为水平垂直居中

发布网友

我来回答

3个回答

热心网友

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="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中的水平垂直居中效果。

热心网友

jQuery将div设置为水平垂直居中代码参考:

$(document).ready(function(){
                        $(window).resize(function(){
                            $('.mydiv').css({
                                position:'absolute',
                                left: ($(window).width() - $('.container').outerWidth())/2,
                                top: ($(window).height() - $('.container').outerHeight())/2
                            });
                        });
                        // 最初运行函数
                        $(window).resize();
                    });

好处就是不需要知道DIV的具体宽度和高度大小,直接用jQuery就可以实现水平和垂直居中,而且兼容各浏览器,这个方法在很多的弹出层效果中应用。

热心网友

直接上代码吧,jquery设置div1始终居中

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="jquery.js"></script>
  <style>
    .div1{width: 300px;height: 400px;background: red;}
  </style>
</head>
<body>
<div class="div1"></div>
</body>
  <script>
    $('.div1').css({ 
      position:'absolute', 
      left: ($(window).width() - $('.div1').outerWidth())/2, 
      top: ($(window).height() - $('.div1').outerHeight())/2 + $(document).scrollTop() 
    }); 
  </script>
</body>
</html>

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com