Twitter Bootstrap贴有Navbar – 下面的div跳了起来

很难描述问题。 所以,看看这个jsFiddle:

http://jsfiddle.net/xE2m7/

当导航栏固定到顶部时,内容会跳到它下面。

CSS:

.affix { position: fixed; top: 0px; } #above-top { height: 100px; background: black; } 

问题出在哪儿?

这里的问题是,没有办法将导航栏固定到顶部的导航器下方的容器中的其余内容传达给导航栏。 您可以使用更现代的CSS来实现这一点,但请注意,这不会是旧浏览器的修复(事实上,您可能会发现有关postion的问题:旧版浏览器中的固定属性…

 .affix + .container { padding-top:50px } 

这等待直到导航栏被修复,然后将填充添加到它的兄弟的容器中,防止它在导航下“跳跃”。

我的解决方案受@ niaccurshi的启发:

而不是硬编码填充顶部,创建一个不可见的重复元素,占用相同的空间,但只有在原始元素被粘贴时。

JS:

 var $submenu = $(".submenu"); // To account for the affixed submenu being pulled out of the content flow. var $placeholder = $submenu.clone().addClass("affix-placeholder"); $submenu.after($placeholder); $submenu.affix(…); 

CSS:

 .affix-placeholder { /* Doesn't take up space in the content flow initially. */ display: none; } .affix + .affix-placeholder { /* Once we affix the submenu, it *does* take up space in the content flow. But keep it invisible. */ display: block; visibility: hidden; } 

您还可以使用Bootstrap附加事件通过CSS类添加和删除相关元素的填充(或边距):

 // add padding or margin when element is affixed $("#navbar").on("affix.bs.affix", function() { return $("#main").addClass("padded"); }); // remove it when unaffixed $("#navbar").on("affix-top.bs.affix", function() { return $("#main").removeClass("padded"); }); 

这是一个JSFiddle: http : //jsfiddle.net/mumcmujg/1/

另一种方法是,如果您想避免重复内容。