简体   繁体   English

粘性div-在特定点停止滚动

[英]Sticky div - stop scrolling at certain point

I have a fixed div that follows the page when it scrolls past the top of the page. 当页面滚动到页面顶部上方时,我在页面之后有一个固定的div。

I would like it to stop scrolling once it reaches the bottom of a particular div. 我希望它到达特定div的底部时停止滚动。 I am not great with javascript. 我对javascript不太满意。

Basically needs to remove the class .affix. 基本上需要删除类.affix。 But it might need an offset so that it doesn't overlap into the layout below. 但是它可能需要一个偏移量,以使其不会重叠到下面的布局中。

I have looked at other articles but the div starts off fixed whereas mine becomes fixed. 我看过其他文章,但是div开始是固定的,而我的却是固定的。

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

Javascript: 使用Javascript:

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

Any help would be appreciated 任何帮助,将不胜感激

Lee 背风处

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'});
      }
    });
  }
});

You can also try it just add JavaScript. 您也可以尝试添加JavaScript。 it will automatic calculate height of left panel. 它将自动计算左面板的高度。 you need to change in css when it remove the css. 您需要在移除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
        }

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM