Jquery 根据div的高度动态更改其上边距

Jquery 根据div的高度动态更改其上边距,jquery,Jquery,我有一个div,它固定在网页的侧面。我需要那个div垂直居中。使用CSS很容易完成:(注意:div的基本高度是300px;) 我遇到的问题是这个侧面板div保存了我的站点导航。当导航打开以显示子元素时,它的高度会增加,这会弄乱居中。我需要一些jQuery来重新计算侧面板div的高度,并应用适当的负边距来保持div居中。以下是我使用的jQuery: $("#sidePanel").css("margin-top", $(this).outerHeight()); 我还没有进行过将负边距设置为高度

我有一个div,它固定在网页的侧面。我需要那个div垂直居中。使用CSS很容易完成:(注意:div的基本高度是300px;)

我遇到的问题是这个侧面板div保存了我的站点导航。当导航打开以显示子元素时,它的高度会增加,这会弄乱居中。我需要一些jQuery来重新计算侧面板div的高度,并应用适当的负边距来保持div居中。以下是我使用的jQuery:

$("#sidePanel").css("margin-top", $(this).outerHeight());

我还没有进行过将负边距设置为高度的一半的计算,但这并没有给出我想要的高度值。任何建议???

不涉及
#侧面板
元素。在这种情况下,您需要使用如下传递的函数进行设置:

$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
$("#sidePanel").each(function() {
  $(this).css("margin-top", $(this).outerHeight());
});
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
或者一个电话,像这样:

$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
$("#sidePanel").each(function() {
  $(this).css("margin-top", $(this).outerHeight());
});
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
或者缓存选择器,如下所示:

$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
$("#sidePanel").each(function() {
  $(this).css("margin-top", $(this).outerHeight());
});
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());

尝试将边距设置为窗的高度减去div的高度,全部除以2。这应该使它垂直居中。

谢谢尼克,这很有意义。什么是使其成为负数的最简单方法???@mmsa-只需添加一个
-
:)例如
-$(this).outerHeight()
我是jQuery新手。抓住窗户高度最简单的方法是什么?