这是我的代码
// Get the navbar
let navbar = document.getElementById("navigation");
// Get the offset position of the navbar
let 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 stickyNavigation() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("-sticky");
} else {
navbar.classList.remove("-sticky");
}
}
$(window).scroll(stickyNavigation);
stickyNavigation();
我有一些页面没有导航栏,并且显示错误“未捕获的类型错误:无法读取 null 的属性‘offsetTop’”。如何为此做出 if/else 语句?
我已经尝试过这个:
if (navbar.length > 0) {
}
但是没有成功。
最佳答案
如果在某些情况下没有导航栏,请使用如下语句:
if (navbar) {
//some statements
} else {...}
关于javascript - 未捕获的类型错误 : Cannot read property 'offsetTop' of null (navbar),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53557731/