我将使用HTML、CSS和JavaScript来创建一个具有粘性和响应式导航栏的网页。我已经创建了响应式导航栏并尝试使其成为粘性的。但问题是它不是粘性的,还显示错误:Uncaught TypeError: Cannot read property 'offsetTop' of null。
HTML代码:
如果我使用class而不是id,那么就会显示错误:Uncaught TypeError: Cannot read property 'remove' of undefined。
HTML代码:
<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#career">Careers</a>
<a href="#fellowship">About Us</a>
<a href="javascript:void(0);" class="icon" onclick="myFunctionForResponsive()">
<i class="fas fa-bars"></i>
</a>
</div>
JavaScript代码:
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunctionForSticky()};
// Get the navbar
var navbar = document.getElementById("myTopnav");
// Get the offset position of the navbar
var sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position.
Remove "sticky" when you leave the scroll position
function myFunctionForSticky() {
if(window.pageYOffset >= sticky){
console.log("window.pageYOffset >= sticky");
}
else{
console.log("Not window.pageYOffset >= sticky");
}
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
}
/*Toggle between adding and removing the "responsive" class to topnav
when the user clicks on the icon*/
function myFunctionForResponsive() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
如果我使用class而不是id,那么就会显示错误:Uncaught TypeError: Cannot read property 'remove' of undefined。