我有一个固定在网页一侧的 div。我需要该 div 垂直居中。使用 CSS 轻松完成:(注意:div 的基础高度为 300px;)
#sidePanel { margin: -150px 0 0 0; top: 50%; position: fixed;}
我遇到的问题是这个 sidePanel div 保存了我的网站导航。当导航打开显示子元素时,它的高度会增加,从而扰乱居中。我需要一些 jQuery 来重新计算 sidePanel div 的高度并应用适当的负边距以保持 div 居中。这是我正在使用的 jQuery:
$("#sidePanel").css("margin-top", $(this).outerHeight());
我还没有进行计算以将负边距设置为高度的一半,但这并没有给我我正在寻找的高度值。有什么建议么??
this
不指的是#sidePanel
在这种情况下,您需要使用传入的函数来创建它.css() http://api.jquery.com/css/#css2像这样:
$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });
Or a .each() http://api.jquery.com/each/调用,像这样:
$("#sidePanel").each(function() {
$(this).css("margin-top", $(this).outerHeight());
});
或者缓存选择器,如下所示:
var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)