简体   繁体   English

jQuery居中div到窗口垂直调整大小问题

[英]jQuery centering div to window vertically resizing issue

I am using this method to center a div vertically on my page: 我正在使用此方法将div在页面上垂直居中:

$(window).resize(function() {
    $('.container').css({
        top : ($(window).height() - $('.container').outerHeight()) / 2
    });
});
$(window).resize();

But the code doesn't work initially. 但是代码最初不起作用。 I couldn't figure out what was going on until I tried physically resizing the window while the page is loading. 在页面加载期间尝试物理调整窗口大小之前,我不知道发生了什么。 As soon as I physically resize the browser window, the div centered immediately. 当我实际调整浏览器窗口的大小时,div立即居中。 Any way around this? 可以解决吗? Why is that happening in the first place? 为什么首先发生这种情况?

Thanks! 谢谢!

You need to run this code on load as well as on resize 您需要在加载以及调整大小时运行此代码

$(document).ready(function(){
    $('.container').css({
        top : ($(window).height() - $('.container').outerHeight()) / 2
    });


    $(window).resize(function() {
        $('.container').css({
            top : ($(window).height() - $('.container').outerHeight()) / 2
        });
    });
});

The way I accomplished similar code is to define a helper function that centers the div (in the jquery onDocumentReady): 我完成类似代码的方法是定义一个将div居中的辅助函数(在jquery onDocumentReady中):

$(function () {

    function _centerDiv() {
        $('.container').css({
            top : ($(window).height() - $('.container').outerHeight()) / 2
        });
    }

    _centerDiv();
}

I then hooked into the window's resize event: 然后,我迷上了窗口的resize事件:

    $(window).resize(function () {
        _centerDiv();
    }

When you want to programmatically trigger it (either on-load in the document ready, as above, or to any other event, just call the helper function. 当您要以编程方式触发它时(如上所述,在文档准备就绪时正在加载,或发生任何其他事件,只需调用辅助函数即可。

John 约翰

Check this JSBin 检查此JSBin

I added positioning: 我添加了定位:

 position: 'absolute'

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

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