TypeError jQuery offset().top 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21477560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:35:22  来源:igfitidea点击:

TypeError jQuery offset().top is undefined

jquerycssoffsettypeerror

提问by K7Buoy

The Firefox debugger is showing a TypeError for a jQuery function aimed at sticking a navbar to the to the top of the page when a user scrolls and updating the class at the same time.

Firefox 调试器显示 jQuery 函数的 TypeError 旨在当用户滚动并同时更新类时将导航栏粘贴到页面顶部。

The function is below.

功能如下。

$(window).scroll(function() {
    if ($(".navbar").offset().top>30) {
        $(".navbar-fixed-top").addClass("sticky");
    }
    else {
        $(".navbar-fixed-top").removeClass("sticky");
    }
});

The resulting error is this.

由此产生的错误是这样的。

Timestamp: 31/01/2014 10:01:04

Error: TypeError: $(...).offset(...)is undefined

时间戳:31/01/2014 10:01:04

错误:类型错误:$(...).offset(...)未定义

I have looked about on SO for a similar example but can not translate the outcomes into a fix. Any help would be greatly appreciated.

我已经在 SO 上查看了类似的示例,但无法将结果转换为修复程序。任何帮助将不胜感激。

回答by user3709748

It 's because your $(".navbar") cannot be found. Check if the element exist before getting offset.

这是因为找不到您的 $(".navbar") 。在获取偏移量之前检查元素是否存在。

if ($(".navbar").length) {...}