Twitter Bootstrap Affixed Navbar - div below jumps

2019-01-22 21:07发布

Rather hard to describe the problem. So just look at this jsFiddle:

http://jsfiddle.net/xE2m7/

When the navbar gets fixed to the top the content jumps below it.

CSS:

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

Where is the problem?

4条回答
We Are One
2楼-- · 2019-01-22 21:15

My solution, inspired by @niaccurshi's:

Instead of hard-coding a padding-top, create an invisible duplicate element that takes up the same amount of space, but only while the original element is affixed.

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;
}
查看更多
叛逆
3楼-- · 2019-01-22 21:17

The problem here is that there is no way communicated to the rest of the content in the container below the nav that the nav bar has been fixed to the top. You can achieve this using more modern CSS, but be aware that this won't be a fix for older browsers (and indeed there are issues you may find with postion:fixed properties in older browsers too...

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

This waits until the nav bar is fixed, and then adds padding to the container that is it's sibling, keeping it from "jumping" under the nav.

查看更多
贪生不怕死
4楼-- · 2019-01-22 21:36

An alternative, if you want to avoid duplicate content.

<script>
    jQuery(document).ready(function(){
        jQuery("<div class='affix-placeholder'></div>").insertAfter(".submenu:last");
    });
</script>

<style>
.affix-placeholder {
  display: none;
}
.affix + .affix-placeholder {
  display: block;
  visibility: hidden;
  height: /* same as your affix element */;
  width: 100%;
  overflow: auto;
}
</style>
查看更多
何必那么认真
5楼-- · 2019-01-22 21:38

You can also use Bootstrap affix events to add and remove padding (or margin) from the relevant element via CSS classes:

// 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");
});

Here's a JSFiddle: http://jsfiddle.net/mumcmujg/1/

查看更多
登录 后发表回答