根据其高度动态更改div的顶部边距
我有一个固定在我的网页侧面的div。我需要该div垂直居中。使用CSS很容易完成:(注意:div的底座高度为300像素;)根据其高度动态更改div的顶部边距
#sidePanel { margin: -150px 0 0 0; top: 50%; position: fixed;}
我遇到的问题是这样的侧面板的div持有我的网站导航。当导航系统打开显示子元素时,它的高度会增大,从而扰乱居中。我需要一些jQuery重新计算sidePanel div的高度,并应用适当的负边距来保持div居中。下面是我用打了jQuery:
$("#sidePanel").css("margin-top", $(this).outerHeight());
我还没有计算到negaitve边距设置为高度的一半工作,但这并不是给我高度值我在寻找。有什么建议么??
this
不指#sidePanel
元素在这种情况下,你需要要么传入.css()
这样的功能,使其:
$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
还是一个.each()
调用,就像这样:
$("#sidePanel").each(function() {
$(this).css("margin-top", $(this).outerHeight());
});
或高速缓存的选择,就像这样:
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
尝试将边距设置为窗口高度减去div的高度,除以二。这应该垂直居中。
我是jQuery的新手。抓住窗户高度的最简单方法是什么? – 2010-11-10 22:32:01
$(window).height(); – 2010-11-10 22:32:42
感谢尼克,这很有道理。什么是最简单的方法,使这个负数? – 2010-11-10 22:29:01
@mmsa - 只需添加一个'-' :)例如' - $(this).outerHeight()' – 2010-11-10 22:31:36
哈,现在我觉得很蠢!谢谢,这完美的作品! – 2010-11-10 22:34:10