gpt4 book ai didi

javascript - 导航栏不粘

转载 作者:行者123 更新时间:2023-11-30 09:11:49 26 4
gpt4 key购买 nike

我对网站编码还比较陌生,在堆栈溢出方面没有太多经验。出于某种原因,我的导航栏似乎不想坚持下去。我四处搜索但找不到任何明显的问题。感谢您的帮助!

HTML

<script>
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");
}
}
</script>

</head>
<body>

<div class="navbar" id="navbar">
<a href="Contact.html">Contact</a>
<a href="Passion.html">My Passions</a>
<a href="About.html">About</a>
<a class="active" href="index.html">Home</a>
</div>

CSS

.navbar {
overflow: hidden;
background-color: #333;
}

.navbar a{
float: right;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

.navbar a:hover {
background-color: #ddd;
color: black;
}

.navbar a.active {
background-color: #4CAF50;
color: white;
}

.content {
padding: 16px;
}

.sticky {
position: fixed;
top: 0;
width: 100%;
}

.sticky + .content {
padding-top: 60px;
}

如果您需要我提供任何其他帮助,请告诉我。

最佳答案

您只需将 sticky 类留在 navbar 中即可解决此问题:

//just to occupy space
var cad='<br>';
for(i=0;i<1000;i++){
cad+="<p>Something</p>";

}

document.getElementById('content').textContent=cad;
.navbar {
overflow: hidden;
background-color: #333;
}

.navbar a{
float: right;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

.navbar a:hover {
background-color: #ddd;
color: black;
}

.navbar a.active {
background-color: #4CAF50;
color: white;
}

.content {
padding: 16px;
}

.sticky {
position: fixed;
top: 0;
width: 100%;
}

.sticky + .content {
padding-top: 60px;
}
<body>

<div class="navbar sticky" id="navbar">
<a href="Contact.html">Contact</a>
<a href="Passion.html">My Passions</a>
<a href="About.html">About</a>
<a class="active" href="index.html">Home</a>
</div>

<div id="content">

关于javascript - 导航栏不粘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147548/

26 4 0