我正在尝试创建一个固定的侧边栏菜单。一切正常,但如果你滚动到顶部,侧边栏元素会闪烁。
var windowHeight = $(window).height();
var headerHeight = $('.js-site-header').outerHeight();
var sidebarThreeBlocks = (windowHeight-headerHeight)/3;
var sidebarTwoBlocks = (windowHeight-headerHeight)/2;
var sidebar = $('.js-sidebar');
$('.js-triple-nav a').css({height: sidebarThreeBlocks});
$('.js-double-nav a').css({height: sidebarTwoBlocks});
if (!!sidebar.offset()) {
$(window).scroll(function(){
var stickyTopSidebar = sidebar.offset().top;
var windowTop = ($(window).scrollTop())+headerHeight;
if (stickyTopSidebar < windowTop) {
sidebar.css({ top: windowTop });
}
else {
sidebar.css({ top: '3.125em' });
}
});
}
我过去常常将var stickyTopSidebar = sidebar.offset().top;
放在所有其他变量上,但我总是会在javascript控制台上出错,因为它似乎是未定义的变量。即便如此,侧边栏然后工作完美,没有闪烁,但所有其余的JavaScript都无法正常工作。任何提示或帮助?