2016-11-10 124 views
2

我试图让边距和下边距居中我<div>。我写的这个JavaScript起作用。但是,如果该站点缓存一次,则CTRL + F5刷新将导致脚本收到错误的clientHeight。第二次刷新,检索正确的clientHeight居中DIV保证金顶部和底部边距

我使用window.load尝试和工作原理。但是,它的速度非常缓慢,以至于在加载之后以及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

请给一个链接到的jsfiddle或上传到这里的代码 –

+1

作为替代方案,我相信你可以垂直或水平居中一个div使用标准的CSS和设置利润率:50%。这可能是更简单的解决方案。 Google for css垂直对齐div或类似。 –

+0

请添加'html'和'css'。或者,简而言之,请创建一个[snippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)或[bin](http: //jsbin.com) –

回答

0

使用调整大小事件,因为即使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(); 
相关问题