发布网友
共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(){好处就是不需要知道DIV的具体宽度和高度大小,直接用jQuery就可以实现水平和垂直居中,而且兼容各浏览器,这个方法在很多的弹出层效果中应用。
热心网友
直接上代码吧,jquery设置div1始终居中
<!DOCTYPE html>