我一次又一次地尝试找出粘性导航,我认为这与我的JavaScript的一部分有关。我还包括了我的html和CSS,以防万一出现错误。
编辑:我用错了前面的陈述,我希望菜单在设定点滚动后仍停留在顶部。一旦我向上滚动,我希望它回到这一点。谢谢。
HTML代码
<!--Navigation Menu-->
<div id="navbar">
<a href="#home">Home</a>
<a href="#relationships">Relationships</a>
<a href="#beauty">Beauty</a>
<a href="#entertainment">Entertainment</a>
<a href="#selfcare">Self Care</a>
</div>
CSS代码
#navbar {
overflow: hidden;
background-color: black;
}
#navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px;
text-decoration: none;
font-family: HighTide Sans;
}
.content {
padding: 16px;
}
.sticky {
postion: fixed;
top: 0;
width: 100%;
}
.sticky + .content {
padding-top: 60px;
}
JS代码
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
答案 0 :(得分:0)
您在CSS中拼写的“位置”错误。应该是:
.sticky {
position: fixed;
top: 0;
width: 100%;
}
答案 1 :(得分:0)
我认为您的导航栏需要让该类在页面加载时保持粘性:
window.onscroll = function() {
myFunction()
};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
#navbar {
overflow: hidden;
background-color: black;
}
#navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px;
text-decoration: none;
font-family: HighTide Sans;
}
.content {
padding: 16px;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky+.content {
padding-top: 60px;
}
<!--Navigation Menu-->
<div id="navbar" class="sticky">
<a href="#home">Home</a>
<a href="#relationships">Relationships</a>
<a href="#beauty">Beauty</a>
<a href="#entertainment">Entertainment</a>
<a href="#selfcare">Self Care</a>
</div>
<div style="min-height:1000px;"></div>