如何使用jquery动态设置div的高度? [英] How do I use jquery to dynamically set the height of a div?
本文介绍了如何使用jquery动态设置div的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,但是不起作用(div始终浮动在页面的顶部.我希望它位于页面的中央).
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%";
});
我在做什么错了?
推荐答案
$(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动态设置div的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文