所以我一直在使用这个功能来隐藏/显示带有 anchor 链接的滚动菜单。
它似乎按预期工作,但是我收到了一个恼人的控制台错误:
未捕获的类型错误:无法读取未定义的属性“top”。
有什么建议吗,我错过了什么?
$(document).ready(function () {
"use strict";
var a = !1,
b = $(".menu-wrapper"),
c = $(".menu a"),
d = $(".intro-wrapper");
b.hide(), $("a[href*=#]:not([href=#])").click(function () {
var a = $(this.hash);
return ($(this).addClass("active"), $("html, body").stop().animate({
scrollTop: a.offset().top
}, 1e3), !1);
}),
$(window).scroll(function () {
var g = $(this).scrollTop(),
h = $(this).height(),
i = d.height();
g >= i && !a ? (a = !0, b.stop().fadeIn()) : i > g && a && (a = !1, b.stop().fadeOut()), c.each(function () {
var a = $(this.hash),
b = a.offset().top,
c = b + a.outerHeight();
g + 1 > b && c > g + 1 ? $(this).addClass("active") : $(this).removeClass("active");
});
});
});
最佳答案
显然,这一行:
var a = $(this.hash);
...可能导致 jQuery 集合中没有任何内容(例如,this.hash
不识别页面上的任何元素)。当您在一个空的 jQuery 集上调用 offset
时,它会返回 undefined
(与大多数其他 jQuery“getter”函数一样)。
所以要么:
确定为什么您期望的元素
$(this.hash)
不存在并修复它,或者当
a
是一个空的 jQuery 集时,请注意不要尝试使用offset
的代码,例如:var a = $(this.hash); if (a[0]) { $(this).addClass("active"); $("html, body").stop().animate({ scrollTop: a.offset().top }, 1e3); } return false;
或者如果你真的想像以前的代码一样缩小/混淆它:
var a = $(this.hash); return (a[0] && ($(this).addClass("active"), $("html, body").stop().animate({ scrollTop: a.offset().top }, 1e3)), !1);
关于javascript - 了解此控制台错误 - 'top' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717787/