2015-01-15 96 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