将div上边距和下边距居中

时间:2016-11-10 09:59:32

标签: javascript jquery html

我正试图获得margin-top和margin-bottom以使我的<div>居中。我写的这个JavaScript很有用。但是,如果站点缓存一次, CTRL + F5 刷新会导致脚本收到错误的clientHeight。刷新第二次,检索正确的clientHeight

我尝试过使用window.load,这很有效。然而,<div>加载速度太慢,2秒后,它会转移到中间位置。

<script type="text/javascript">
  var height = $(window).height();
  var clientHeight = document.getElementById('account-wall').clientHeight;
  var calc_height = (height - clientHeight) / 2;
  document.getElementById("account-wall").style.marginTop = calc_height + 'px';
  document.getElementById("account-wall").style.marginBottom = calc_height + 'px';
</script>


<script type="text/javascript">
  $(window).load(function() {
    var height = $(window).height();
    console.log(height);
    var clientHeight = $('.account-wall').height();
    console.log(clientHeight);
    var calc_height = (height - clientHeight) / 2;
    document.getElementById("account-wall").style.marginTop = calc_height + 'px';
    document.getElementById("account-wall").style.marginBottom = calc_height + 'px';
  });
</script>

1 个答案:

答案 0 :(得分:0)

使用resize事件,因为即使window.height发生更改,您也需要居中。要确保它从开始使用.resize()来触发事件。

$(window).on('resize', function(event){
  var height = $(window).height();
  console.log(height);
  var clientHeight = $('.account-wall').height();
  console.log(clientHeight);
  var calc_height = (height - clientHeight)/2;
  document.getElementById("account-wall").style.marginTop = calc_height+'px';
  document.getElementById("account-wall").style.marginBottom =         calc_height+'px';
}).resize();