Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

javascript - Bootstrap affix dynamically on resize

I have a 100% height div with a nav underneath it and more content under that.

When the user scrolls passed the nav it sticks to the top of the page and when the user goes back to the 100% height div the nav is left behind.

As the div is 100% height the 'data-offset-top' for the nav needs to change dynamically.

The following code works for that:

    $('#navigation').affix({
        offset: {
            top: $('#hero').height()
        }
    });

However when I resize the page the value of the offset does not get readded to the offset.

The following code checks for the page height to change and then gives the new height to the data-offset-top but it does not ` function affixChange() {

     $('#navigation').attr('data-offset-top', $('#hero').height());
    $('#navigation').affix({
        offset: {
            top: $('#hero').height()
        }
    }); 
 }

affixChange();
setInterval(function(){
 affixChange();
console.log($('#hero').height());
}, 1000)
  1. Why is my method not working?
  2. Is there a better way to do this?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bootstrap gives you the possibility to pass a function to calculate the offset dynamically:

$('#navigation').affix({
  offset: {
    top: function() { return $('#hero').height(); }
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...