javascript - 未捕获的类型错误 : Cannot read property 'offsetTop' of null (navbar)

标签 javascript jquery

这是我的代码

// 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/

相关文章:

javascript - 如何使用 React Hooks 更新对象内数组的特定值?

javascript - JavaScript 中的赋值和 var 关键字

javascript - 使用复选框突出显示特定表

javascript - 选择 html 元素 1,2,5,6 ...元素数量未知的优雅方法/

javascript - Angular 旋转木马在旋转木马末端添加了额外的空幻灯片

Javascript 返回封闭函数

javascript - 脚本未执行并且脚本不工作

jquery - 更改事件缩略图 Ninja Slider 的样式

javascript - 为什么wordpress要把jquery放在前面?

javascript - jquery .on 本身