我有一个“粘性导航”,当用户向下滚动时“粘”到顶部(函数将其位置更改为:fixed,top:0)。我在页面顶部还有一个“expandalbe”登录区域。第一个问题是当我扩展页面顶部的登录区域时,导航栏“粘住”的点发生了变化。现在我让它在面板打开时粘住,但是当它关闭时,它粘在错误的点(似乎粘在#panel的额外高度点)。见小提琴
如何使#sticky_navigation 在两种情况下都保持在顶部:0 - 当#panel 打开和关闭/默认时?
(删除了无效的 YouTube 链接)
谢谢
**// FIRST VERSION sticky navigaiton ------------//**
$(document).ready(function(){
var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop(); // our current vertical position from the top
if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 })
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
}
};
sticky_navigation();
$(window).scroll(function() {
sticky_navigation();
});
});
更新: 现在我只有在#panel 打开时才能使用它。如果它关闭,#sticky_navigation 不会启动。
//sticky top nav PANEL OPEN ONLY
$(document).ready(function(){
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
// our function that decides weather the navigation bar should have "fixed" css position or not.
var sticky_navigation2 = function(){
var scroll_top1 = $(window).scrollTop(); // our current vertical position from the top
scroll_top1 = $(window).scrollTop() - $('#panel').height();
// if we've scrolled more than the navigation, change its position to fixed to stick to top,
// otherwise change it back to relative
if (scroll_top1 > sticky_navigation_offset_top ) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':0, 'left':0 })
} else {
$('#sticky_navigation').css({ 'position': 'relative' });
}
};
// run our function on load
sticky_navigation2();
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation2();
});
});