문제

Let me explain the situation:

There is a relative positioned sidebar. After scrolling past the top of the main-content this sidebar changes to absolute and is then real-time updated to the top position in the window (scrollTop of the window).

The problem is that it is really slow and choppy (in Firefox) because it is updating the whole time. How can I update the position 'real-time' without so much load?

Currently it looks like this:

var headerOffset = $('#main-content').offset().top;
$(document).on('scroll', function() {
  if( ($(document).scrollTop() + 15) > $('#main-content').offset().top ){
    $('#sidebar').addClass('fixed');
    $('#sidebar').css('top', ( $(document).scrollTop() - headerOffset) + 15 );
  } else {
    $('#sidebar').removeClass('fixed');
  }
});

Thanks in advance :)

도움이 되었습니까?

해결책

In case you want to do all the Javascript hassle because you have unpredictable headers and don't know the exact position of main content it wold be enough to set the ccs to fixed and just calculate the position on start.

var headerOffset = $('#main-content').offset().top;
$('#sidebar').css('top', headerOffset);

like here:http://jsfiddle.net/4amdr/

Thats the only way I can imagine why you don't want to use a fixed top and leave js out.

다른 팁

you should use affix from twitter bootstrap : Bootstrap's affix

What about this :

=> http://jsfiddle.net/8XVXj/1/ or a full exemple : http://jsfiddle.net/8XVXj/2/

var headerOffset = $('#main-content').offset().top;
$(document).on('scroll', function(){
 if( ($(document).scrollTop() + 15) > $('#main-content').offset().top ){
   if($('#sidebar').hasClass('fixed') === false) {
     $('#sidebar').addClass('fixed');
     $('#sidebar').css('top', ($(document).scrollTop() - headerOffset) + 15 );
   }
 } else {
   $('#sidebar').removeClass('fixed');
 }
});

I add only once the position fixed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top