jQuery 根据高度动态更改 div 的上边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4149701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically change the top margin of a div based on its height
提问by Mike Muller
I have a div that is fixed to the side of my web page. I need that div to be centered vertically. Easily accomplished using CSS: (note: the base height of the div is 300px;)
我有一个固定在我网页一侧的 div。我需要该 div 垂直居中。使用 CSS 轻松完成:(注意:div 的基本高度为 300px;)
#sidePanel { margin: -150px 0 0 0; top: 50%; position: fixed;}
The issue I'm having is this sidePanel div holds my site navigation. When the nav opens up to show child elements, it grows in height which messes up the centering. I need some jQuery to re-calculate the height of the sidePanel div and the apply the appropriate negative margin to keep the div centered. Here is the jQuery I was playing with:
我遇到的问题是这个 sidePanel div 包含我的网站导航。当导航打开以显示子元素时,它的高度会增加,这会扰乱居中。我需要一些 jQuery 来重新计算 sidePanel div 的高度并应用适当的负边距以保持 div 居中。这是我正在玩的jQuery:
$("#sidePanel").css("margin-top", $(this).outerHeight());
I have not worked on the calculation to set the negaitve margin to half of the height, but this is not giving me the height value I'm looking for. Any suggestions??
我还没有计算将负边距设置为高度的一半,但这并没有给我我正在寻找的高度值。有什么建议??
回答by Nick Craver
this
doesn't refer to the #sidePanel
element in this case, you would need to either make it with a function passed into .css()
like this:
this
#sidePanel
在这种情况下不引用元素,您需要使用传入的函数来制作它,.css()
如下所示:
$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
Or a .each()
call, like this:
或者打个.each()
电话,像这样:
$("#sidePanel").each(function() {
$(this).css("margin-top", $(this).outerHeight());
});
Or cache the selector, like this:
或者缓存选择器,像这样:
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
回答by Aaron Hathaway
Try setting the margin to the window's height minus the div's height, all divided by two. That should center it vertically.
尝试将边距设置为窗口的高度减去 div 的高度,然后全部除以 2。那应该垂直居中。