2011-09-29 33 views

回答

4

執行以下操作:

  1. $(window)創建scroll event handler
  2. 在此事件處理程序中,檢查用戶是否滾動得比您始終想要查看的元素的頂部低。您可以使用offestscrollTop方法來執行此操作。
  3. 如果是,請使用top: 0將元素設置爲position: fixed。您可能還需要調整左側屬性,具體取決於您的佈局。
  4. 如果否,請將元素設置爲position: static
+0

你試過了什麼嗎?在http://jsfiddle.net上放一下。如果你卡住了,我會幫忙的。 – Pat

1

創建完全相同的行爲9gag.com代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<!-- tags html, header, body, divs, anything --> 

<div id="post-control-bar" class="spread-bar-wrap"> 
    <div class="spread-bar" style="width:600px"> 
     Facebook button, Twitter button, anything... 
    </div> 
</div> 

<script type="text/javascript"> 
window.onscroll = function() 
{ 
    if(window.XMLHttpRequest) { 
     if (document.documentElement.scrollTop > 173 || self.pageYOffset > 173) { 
      $('post-control-bar').style.position = 'fixed'; 
      $('post-control-bar').style.top = '0'; 
     } else if (document.documentElement.scrollTop < 173 || self.pageYOffset < 173) { 
      $('post-control-bar').style.position = 'absolute'; 
      $('post-control-bar').style.top = ''; 
     } 
    } 
} 
</script> 

<!-- content, footer, anything --> 
相關問題