How do I use jquery to dynamically set the height

2019-08-19 11:10发布

问题:

Here is my code, but it doesn't work (the div always floats to the top of the page. I want it to be located in the center of the page).

HTML:

<div id="overlay">Stuff</div>

JQuery:

$(document).ready(function(){
    var height = $('#overlay').height();
    var marginTop = (height)/2;
    document.getElementById("overlay").style.marginTop="-"+marginTop+"px";
    document.getElementById("overlay").style.top="50%";
});

What am I doing wrong?

回答1:

$(document).ready(function(){
    resize();
    $(window).resize(resize);
});

function resize()
{
    var height = $('#overlay').height();
    $('#overlay').css('margin-top', (($(window).height() - height) / 2) + 'px');
}

Remember, you want the window height minus the overlay height. Then divide by two and you have your desired margin.



标签: jquery height