JS实现div动态水平垂直居中

来源:互联网 发布:win10 mac地址修改 编辑:程序博客网 时间:2024/06/10 16:30
<div class="bouncingScreen-bg" id="bouncingScreen-bg"></div>

<div class="bouncingScreenBox"  id="bouncingScreen"></div>

样式如下:

<style>

.bouncingScreen-bg{
width: 100%;
height: 100%;
background: #000;
opacity: 0.6;
position: absolute;
}
.bouncingScreen-content{
position: relative;
}


.bouncingScreenBox{
width: 80%;
margin-left: 10%;
margin-right: 10%;
}

</style>

把id为bouncingScreen的元素整个页面居中

首先水平居中很简单;

其次是垂直居中。分为三步:

1)获取到当前屏幕的高度;

2)获取到需要居中的div的高度;

3)用屏幕的高度减去div的高度除以2就是需要给div设计的margin-top/padding-top的值。

js代买块:

<script type="text/javascript">
  window.onload=function(){
  var hBscreen=window.screen.height;
  var bScreen=document.getElementById("bouncingScreen");
  var padding_top=(hBscreen-bScreen.offsetHeight)/2;       //因为此div在页面中只用了一次且以后不会改变,所以写了数值,如果是不确定的,获取到高度放着这里就可以
  bScreen.style.paddingTop = padding_top + "px";

        document.getElementById("bouncingScreen-bg").offsetHeight=hBscreen;
  };
</script>