2014-10-03 143 views
0

我一直想知道如何在滾動時讓div元素停留在頁面頂部,就像我在某些網站上看到的一樣。我見過很多解決方案,但他們不適合我,我不確定爲什麼。html - 如何讓一個div元素停留在頂部,而你滾動?

所以我一直在尋找如何做到這一點很久,最近我得到了this,但似乎有什麼不對。 我的JS是這樣的:

var navTop = $('.nav').offset().top; 
$(window).scroll(function() { 
    var currentScroll = $(window).scrollTop(); 
    if (currentScroll >= navTop) { 
     $('.nav').css({ 
      position: 'fixed', 
      top: '0', 
      left: '0' 
     }); 
    } else { 
     $('.nav').css({ 
      position: 'static' 
     }); 
    } 
}); 

而我的HTML是:

<!DOCTYPE html> 
<html> 

<head> 
<script src="scrll.js"></script> 
<style> 
a:link { 
color:#000000; background-color:transparent 
} 
a:visited { 
color:#000000; background-color:transparent 
} 
a:hover { 
color:#000000; background-color:transparent 
} 
a:active { 
color:#000000; background-color:transparent 
} 
body { 
    height: 3000px; 
} 
#header { 
    background-color:black; 
    color:white; 
    text-align:center; 
    padding:5px; 
    box-shadow: 0px 10px 5px #888888; 
    border-radius: 25px; 
} 
.fixme { 
    line-height:30px; 
    background-color:#eeeeee; 
    height:30px; 
    width:100%; 
    float:left; 
    padding:5px;  
    border-radius: 25px; 
} 
#section { 
    width:350px; 
    float:left; 
    padding:10px;   
} 
</style> 
</head> 

<body> 

<div id="header"> 
<h1 style="font-size: 400%">Website</h1> 
</div> 

<div class="nav"> 
<a href="home.html" style="text-decoration:none"> Home |</a> 
<a href="download.html" style="text-decoration:none"> Activity |</a> 
<a href="https://www.google.com/" style="text-decoration:none" target="_blank"> Google |</a> 
<a href="suggestions.html" style="text-decoration:none"> Suggestions |</a> 
</div> 

<div id="section"> 
<h2>Suggestions</h2> 
<p> 
Herpdaderp 
</p> 
</div> 

</body> 
</html> 

它工作在JSFiddle,但它似乎並不在我的電腦上工作的外部。我甚至直接將代碼粘貼到自己的html文檔中,但即使這樣也能工作。

我相信它與使用javascript的html有關,但我可能是錯的。有沒有人有這方面的幫助?

+0

弄來控制檯(F12)什麼奇怪的是,小提琴是工作,沒有在你的補償 – loveNoHate 2014-10-03 21:17:28

+6

我沒有看到你在你的html代碼中包含_jQuery_。沒有它,它不會工作。 – 2014-10-03 21:17:59

+0

@ t.niese我把它包含在

相關問題