bootstrap-affix : Div underneath affix “jumps” to

2020-06-04 12:00发布

Been playing with boostrap for a few days and amazed at the capabilities it has to offer.

Have been trying to have a "header" of some sorts, which is affixed to the top when the user scrolls down.

You can find my current work here: http://mp3dj.free.fr/affix/site/

However you will notice that, when scrolling down, the "POST 1" suddenlty jumps to the top of the page. i.e there is no smooth scroll behind like here: http://jsfiddle.net/namuol/Uaa3U/

Current code:

<div class="container">
  <div class="row affix-top" data-spy="affix" data-offset-top="60">
    <div class="span12">
      <div class="row">
        <div class="span3">
          <img src="http://www.socialfork.net/public/images/default-profile-photo-female.jpg" class="img-polaroid">
        </div>
      <div class="span9"><h1>Samantha Sam</h1></div>
    </div>
  </div>
</div>
  <div class="row">
    <div class="span12">
      <div id="post1" class="box">
        <h1>Post 1</h1>
        <p> Scroll Down↓</p>
      </div>
      <div id="post2" class="box"><h1>Post 2</h1></div>
      <div id="post3" class="box"><h1>Post 3</h1></div>
     </div>
   </div>   
</div>

Any help appreciated!

2条回答
不美不萌又怎样
2楼-- · 2020-06-04 12:26

What happens in your code is the row at the top changes its position to fixed when its offset to the top is smaller then 60px. The consequence is that it stops to consume any space above the next row.

In the jsfiddle you introduced there is a JS code you should understand and should help you. This one is for you:

$('#nav-wrapper').height($("#nav").height());

It requires your header to be placed yet inside another div (class called nav-wrapper in fiddle). JQuery code above sets its height based on row height during initialization of the page. The height stays the same even if the top row disappears (of getting fixed).

Another part of the JS code:

$('#nav').affix({
    offset: $('#nav').position()
});

​ makes you independent of the size of space above the top row, but in your case I think you do not need it (you can predict it always takes 60px).

查看更多
姐就是有狂的资本
3楼-- · 2020-06-04 12:46

when you use the solution from Marcin Skórzewski mind that if you're using a collapse in your navbar it effects the dropdown.

  • The height of the complete navbar is set using the small piece of JS code.
  • When your window gets smaller the navbar will be replaced with ||| (using default bootstrap)
  • When you're using a dropdown and press ||| to show the dropdown it will be placed behind the content below. It will not slide the content down. This is because the height of the navbar is set.

Possible solution 1: remove the height of the navbar when you click on ||| and place it back again when the dropdown slides back. Possible solution 2: add a margin-top to the next element once the navbar sticks

update: https://stackoverflow.com/a/15177077/1059884 an excellent solution using CSS

查看更多
登录 后发表回答