admin管理员组

文章数量:1403240

I'm trying to use the affix function to attach a header to the top of the screen, but have it attached only for a portion of the page. It should detach (and scroll up along with the content) when the user scrolls past a certain point.

I'm using the script from this jsfiddle.

What I'm trying right now is this:

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

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

With the .detached class like so:

.detached { position: static; }

Can't get this to work. Any suggestions?

I'm trying to use the affix function to attach a header to the top of the screen, but have it attached only for a portion of the page. It should detach (and scroll up along with the content) when the user scrolls past a certain point.

I'm using the script from this jsfiddle.

What I'm trying right now is this:

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

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

With the .detached class like so:

.detached { position: static; }

Can't get this to work. Any suggestions?

Share Improve this question edited Feb 22, 2013 at 21:52 sth 230k56 gold badges287 silver badges370 bronze badges asked Feb 22, 2013 at 20:37 Josh StarkJosh Stark 1311 silver badge3 bronze badges 2
  • I don't think this is possibly with the standard Twitter Bootstrap affix module. – Jesse Commented Feb 22, 2013 at 21:12
  • I think you are looking for a question [answered here.][1] Check out the fiddle. [1]: stackoverflow./questions/15197453/… – Thomas Commented Apr 24, 2013 at 18:16
Add a ment  | 

3 Answers 3

Reset to default 3

Twitter Bootstrap affix module doesn't have that option. But, I've used many times hcSticky, it is awesome. Take a look, it's simply to use and works very well.

You can write the logic in a function, and pass it to affix as offset.top.

Try

var navHeight = $("#nav").height();
var detachTop = $("#detach").offset().top;
var navTop = $("#nav-wrapper").offset().top;

$('#nav-wrapper').height(navHeight);
$('#nav').affix({
    offset : {
        top : function() {
            if ((navHeight + $(window).scrollTop()) > detachTop) {
                return Number.MAX_VALUE;
            }
            return navTop;
        }
    }
});

Fiddle is here.

Another option which might work for you: http://jsfiddle/panchroma/5n9vw/

HTML

<div class="header" data-spy="affix">
affixed header, released after scrolling 100px
</div>   

Javascript

$(document).ready(function(){
$(window).scroll(function(){
var y = $(window).scrollTop();
if( y > 100 ){
  $(".header.affix").css({'position':'static'});
} else {
  $(".header.affix").css({'position':'fixed'});
}
});
})  

Good luck!

本文标签: javascriptAttach and detach affixed headers with Twitter BootstrapStack Overflow