我正在尝试创建一个仅在到达页面顶部后才保持固定的导航栏。我的代码可以正常工作,因此导航是固定的,但我似乎无法让它首先滚动到顶部。
这是 HTML:
<div id= "home"> contentcontentcontent </div>
<div id="nav">
<a href="#home">home</a>
<a href="#gogreen">go green</a>
<a href="#yourarea">your area</a>
<a href="#howto">how to</a></div>
还有 CSS:
nav {
text-align: center;
top: 600;
z-index: 100;
position: fixed;
width: 100%;
border: 0;
margin-bottom: 0;}
fixed {
top:600;
z-index: 100;
position: fixed;
width: 100%;}
home {
overflow: hidden;}
还有 jQuery:
$(document).ready(function() {
$(window).scroll(function () {
//console log determines when nav is fixed
console.log($(window).scrollTop())
if ($(window).scrollTop() > 600) {
$('#nav').addClass('fixed');
}
if ($(window).scrollTop() < 601) {
$('#nav').removeClass('fixed');
}
});
这些是基于对本网站上类似问题的回答,但到目前为止似乎没有任何效果。有谁知道我的代码有什么问题吗?
最佳答案
在编写 CSS 选择器时,id 和类需要分别以 #
或 .
为前缀。在你的 CSS 中你有
nav { // rules }
fixed { // rules }
home { // rules }
什么时候应该有
#nav { // rules }
.fixed { // rules }
#home { // rules }
这是 your code 的 fiddle 工作。
关于javascript - 滚动后固定导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139064/