How do I use jquery to dynamically set the height of a div?

喜你入骨 提交于 2019-12-12 01:43:16

问题


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.



来源:https://stackoverflow.com/questions/13149662/how-do-i-use-jquery-to-dynamically-set-the-height-of-a-div

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!