2015-01-15 81 views
0

我在我的项目中有一个粘性边栏,但是当您转到页面底部时,粘性边栏与我的页脚重叠。jQuery - 粘性元素重叠页脚,如何避免它?

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

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

回答

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

[...] 
+0

但实际上与您的解决方案,我刚开了相同的结果@ roNn23 – TheUnnamed 2015-01-15 16:49:33

+0

我想你可以在这里看到http://codepen.io/maketroli/pen/emvrbG – TheUnnamed 2015-01-15 16:52:58

+0

更好地我的例子噢,抱歉,我的例子很快就被黑了。现在看不到它,对不起。也许以后或明天:/ – roNn23 2015-01-15 16:59:52