使用滚动条在div内滚动侧边栏 - $(window).on('scroll',function()?

时间:2016-04-01 07:31:09

标签: javascript jquery html css

我希望我的社交侧边栏仅在灰色div中进行滚动。我已经把侧边栏放在灰色div内,不超过页脚或上面的内容。我的难点在于伴随滚动的侧边栏滚动而不是灰色div。

http://test.eae.pt/beautyacademy/angebot/

JS:

beautyAcademy.sharer = {
element: void 0,
elementToScroll: void 0,
init:function() {
    this.element = $('.js-sharer-ref');
    console.log(this.element.length);
    if(this.element.length != 1) {
        return;
    }
    this.build();
},
build: function() {
    this.binds();
},
binds: function() {
    var _this = this;
    // Element that's gonna scroll
    this.$elementToScroll = $('.fixed-social');

    // Element that's gonna scroll height
    this.elementToScrollHeight = this.$elementToScroll.outerHeight();

    // Element where scroll is gonna happen Height
    this.elementHeight = this.element.outerHeight();

    // Element where scroll is gonna happen distance to top
    this.elementOffsetTop = this.element.offset().top;

    // Scroll that was done on the page
    this.windowScrollTop = $(window).scrollTop();

    this.elementOffsetBottom = this.elementOffsetTop + this.elementHeight - this.elementToScrollHeight;

    this.$elementToScroll.css('top', (_this.elementOffsetTop+80) + "px");

    $(window).on('scroll', function() {
       if(this.windowScrollTop +  this.elementToScrollHeight < this.elementHeight  )
           this.$elementToScroll.css('margin-top',  this.windowScrollTop );
    });
}
};

1 个答案:

答案 0 :(得分:0)

你需要尝试如下:

 $(function(){
   if ($('#container').length) {
      var el = $('#container');
      var stickyTop = $('#container').offset().top; // returns number
      var stickyHeight = $('#container').height();

      $(window).scroll(function(){ // scroll event
          var limit = $('#footer').offset().top - stickyHeight - 20;

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

DEMO

相关问题