0

我有这个代码:http: //jsfiddle.net/k56yR/1/

但是当浏览器滚动条向下并开始顶部#sticky颤抖时,有人知道如何解决这个问题吗?

这是 jQuery 代码:

$(function(){ // document ready
   if (!!$('#sticky').length) { // make sure "#sticky" element exists
      var el = $('#sticky');
      var stickyTop = $('#sticky').offset().top; // returns number
      var footerTop = $('#footer').offset().top; // returns number
      var stickyHeight = $('#sticky').height();
      var limit = footerTop - stickyHeight - 20;
      $(window).scroll(function(){ // scroll event
          var windowTop = $(window).scrollTop(); // returns number

          if (stickyTop < windowTop){
             el.css({ position: 'fixed', top: 0 });
          }
          else {
             el.css('position','static');
          }

          if (limit < windowTop) {
          var diff = limit - windowTop;
          el.css({top: diff});
          }     
        });
   }
});​
4

1 回答 1

0
<div class="wrapper">
<div class="results">

</div>
  <header>
    Header
    <span></span>
  </header>
  <div class="left">
    <span class="top"></span>
    <div class="nosticky">Nosticky</div>
    <div class="sticky">
    <span class="top"></span>
      <div class="bloc bloc1">
        Bloc 1<br>
        <span></span>
      </div>
      <div class="bloc bloc2">
        Bloc 2
      </div>
      <span class="bottom"></span>
    </div>
    <span class="bottom"></span>
  </div>
  <div class="right">
    Content
    <span></span>
  </div>
  <div class="footer">
    Footer
  </div>
</div>


<script>
var sticky_offsettop = $('.sticky').offset().top;
var sticky_height = $('.sticky').height();
var sidebar_height = $('.left').height();
var empty_space_left = sidebar_height - sticky_height;
var sidebar_offsettop = $('.left').offset().top;
var sidebar_bottom_offsettop = (sidebar_offsettop+sidebar_height);
var margintotop = 20;
$(window).scroll(function() {
    var window_scrolltop = $(window).scrollTop();
  var window_scrolltop_margin = (window_scrolltop+margintotop);
  var realtime_sidebar_bottom_offsettop = (sidebar_bottom_offsettop - window_scrolltop);
  var sticky_height_realtime = $('.sticky').height();

  
    if(window_scrolltop_margin >= sticky_offsettop ){
        $('.bloc').css('background', '#ddd');
     $('.sticky').css('position', 'sticky').css('top', '20px').css('bottom', 'initial');
    }
    if(sticky_offsettop > window_scrolltop_margin ){
        $('.bloc').css('background', '#ddd');
        $('.sticky').css('position', 'relative').css('top', 'initial').css('bottom', 'initial');
    }    
    if(sticky_height_realtime >=  realtime_sidebar_bottom_offsettop ){
        $('.bloc').css('background', '#ddd');
        $('.sticky').css('position', 'absolute').css('top', 'initial').css('position', 'absolute').css('bottom', '0');
    } 
});
<script>

这是我为实现它所做的一个示例:https ://jsfiddle.net/cuopyL51/

于 2021-10-06T16:31:21.960 回答