我正在使用这段代码使我的导航在#header1
div之后粘滞。它对我来说工作正常,但问题是我的控制台显示错误
捕获的类型错误:无法读取未定义的属性"top">
请为我提供一些解决方案。谢谢
$(document).ready(function () {
$(window).bind('scroll', function () {
var navHeight = $(".header1").height();
($(window).scrollTop() > navHeight) ? $('.afterLgnRow').addClass('goToTop') : $('.afterLgnRow').removeClass('goToTop');
});
});
$('.afterLgnRow').affix({
offset: {
top: $('#header1').offset().top
}
});
问题是因为当您尝试在 DOM 准备就绪之前使用#header1
元素时offset()
不返回任何内容。要解决此问题,请移动 document.ready 处理程序中的代码。
另请注意,bind()
已弃用,请改用on()
,您可以通过将toggleClass()
与布尔值一起使用来简化addClass()
/removeClass()
逻辑。
$(document).ready(function () {
$(window).on('scroll', function () {
var navHeight = $(".header1").height();
$('.afterLgnRow').toggleClass('goToTop', $(window).scrollTop() > navHeight);
});
$('.afterLgnRow').affix({
offset: {
top: $('#header1').offset().top
}
});
});
我还注意到您正在访问#header1
和.header1
- 确保这些选择器正确。