jQuery - 粘性元素与页脚重叠,如何避免呢?

时间:2015-01-15 15:58:21

标签: javascript jquery css css3

我的项目有一个粘性侧边栏,但当你转到页面底部时,粘性边栏与我的页脚重叠。

我想要的是当粘性元素到达页脚时,然后就在那里停止,这样用户就可以看到整个页脚。

here is a demonstration of what I have so far.

or a jsfiddle in case it is easier for you

这是代码:

var stickySidebar = $('.sticky');

if (stickySidebar.length > 0) { 
  var stickyHeight = stickySidebar.height(),
      sidebarTop = stickySidebar.offset().top;
}

// on scroll move the sidebar
$(window).scroll(function () {
  if (stickySidebar.length > 0) {   
    var scrollTop = $(window).scrollTop() + 70;

    if (sidebarTop < scrollTop) {
      stickySidebar.stop(true, false).animate({top: scrollTop - sidebarTop});

      // stop the sticky sidebar at the footer to avoid overlapping
      var sidebarBottom = stickySidebar.offset().top + stickyHeight,
          stickyStop = $('.main-content').offset().top + $('.main-content').height();
      if (stickyStop < sidebarBottom) {
        var stopPosition = $('.main-content').height() - stickyHeight;
        stickySidebar.stop(true, true).animate({top: stopPosition});
      }
    }
    else {
      stickySidebar.stop().animate({top: 0});
    } 
  }
});

$(window).resize(function () {
  if (stickySidebar.length > 0) {   
    stickyHeight = stickySidebar.height();
  }
});

1 个答案:

答案 0 :(得分:0)

这可能并不完美,但我认为它给了你正确的想法,如何解决这个问题。如果侧边栏的底部低于页脚的顶部位置,您只需要检查。比停止动画。

http://jsfiddle.net/hdj99b21/1/

[...]

  var stickyTopPos = stickySidebar.offset().top;
  var stickyBottomPos = stickyHeight + stickyTopPos;    
  var footerTopPos = $('footer').offset().top;

  if(stickyBottomPos >= footerTopPos) {
     var stopPosition = footerTopPos - stickyHeight;
     stickySidebar.stop(true, true).css({top: stopPosition});
  }

[...]