2013-02-01 81 views
-2

我已經在頁面底部的固定div這個CSS:jQuery的隱藏的div時頁面滾動

#bottomdiv { 
    display:block; 
    position:fixed; 
    bottom:0px; 
    left:0px; 
    width:100%; 
    text-align:center; 
    height:40px; 
    z-index:999; 
    background-color: transparent; 
    padding: 0 0 0 1px; 
} 

和我有頁腳divclass="footergroup"。現在我需要隱藏<div id="bottomdiv">使用jquery效果當頁面滾動到達頁腳<div class="footergroup"> AND顯示<div id="bottomdiv">當滾動到首頁。

+1

還有,你試過嗎? –

回答

2

我猜你想要頁腳幻覺縮小和堅持當你向上滾動。

要找到相對於屏幕底部的滾動位置,您需要從滾動位置減去視口高度:$(window).scrollTop() - $(window).height()。爲了平滑過渡,還要減去粘性頁腳的高度。

然後,您需要在頁面上找到主頁腳的偏移量。這很容易使用$("#footer").offset()完成。

而對於邏輯,您只需要檢查您的滾動位置是否爲>=您的頁腳從頂部偏移並相應地使用hide()

所有這一切都需要在至少三次完成:

  1. document.load
  2. window.resize
  3. window.scroll

的標記:

<html> 
    <head><title>Sticky Footer</title></head> 
    <body> 
     <div id="footergroup"></div> 
     <div id="bottomdiv"></div> 
    </body> 
</html> 

CSS:

#bottomdiv { 
    position:fixed; 
    bottom:0px; 
    left:0px; 
    width:100%; 
    height:40px; 
    background-color: red; 
} 
#footergroup { 
    height: 200px; 
    background: blue; 
} 
#padding { 
    height: 1000px; 
} 

jQuery的:

$(document).on('load scroll', stickyFooter); 
$(window).on('resize', stickyFooter); 

function stickyFooter() 
{ 
    var $footer = $("#footergroup"); 
    var $stickyFooter = $("#bottomdiv"); 
    var footerOffsetTop = $footer.offset().top; 
    var viewportHeight = $(window).height(); 

    // Subtract your sticky footer's height for a more seamless transition. 
    var scrollPosition = $(this).scrollTop() + viewportHeight - $stickyFooter.outerHeight(); 

    // This is the real magic. 
    if(scrollPosition >= footerOffsetTop) 
    { 
     $stickyFooter.hide(); 
    } 
    else 
    { 
     $stickyFooter.show(); 
    } 
} 

See this code in action.