繁体   English   中英

居中div边距顶部和边距底部

[英]Centering div margin top and margin bottom

我正在尝试使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>

使用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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM