粘性div - 在某一点停止滚动

时间:2017-04-25 09:09:38

标签: javascript jquery css

当页面滚动到页面顶部时,我有一个固定的div跟随页面。

我希望它一旦到达特定div的底部就停止滚动。我用javascript不是很好。

基本上需要删除类.affix。但它可能需要一个偏移量,以便它不会重叠到下面的布局中。

我看过其他文章,但是div开始固定,而我的固定。

JSfiddle:https://jsfiddle.net/8t1ddL2h/

Javascript:

var stickySidebar = $('.sticky-sidebar').offset().top;
        $(window).scroll(function() {  
            if ($(window).scrollTop() > stickySidebar) {
                $('.sticky-sidebar').addClass('affix');
            }
            else {
                $('.sticky-sidebar').removeClass('affix');
            }  
        });

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

Try this Fiddle

$(document).ready(function() {    
  var $sticky = $('.sticky-sidebar');
  var $stickyrStopper = $('.other-content');
  if (!!$sticky.offset()) { // make sure ".sticky" element exists

    var generalSidebarHeight = $sticky.innerHeight();
    var stickyTop = $sticky.offset().top;
    var stickOffset = 0;
    var stickyStopperPosition = $stickyrStopper.offset().top;
    var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
    var diff = stopPoint + stickOffset;

    $(window).scroll(function(){ // scroll event
      var windowTop = $(window).scrollTop(); // returns number

      if (stopPoint < windowTop) {
          $sticky.css({ position: 'absolute', top: diff });
      } else if (stickyTop < windowTop+stickOffset) {
          $sticky.css({ position: 'fixed', top: stickOffset });
      } else {
          $sticky.css({position: 'absolute', top: 'initial'});
      }
    });
  }
});

答案 1 :(得分:1)

您也可以尝试添加JavaScript。它会自动计算左侧面板的高度。你需要在删除css时更改css。

var othercon = $('.other-content').offset().top;
var sliderheight = $( ".sticky-sidebar" ).height();
$(window).scroll(function() {  
        if ($(window).scrollTop() >= othercon-sliderheight) {
            $('.sticky-sidebar').removeClass('affix');
              // need to change here according to your need
        }

    });