我遇到了一个问题,我无法解决我用来在向下滚动页面时使用粘性导航的代码。
我希望JS如果浏览器窗口宽度低于720px,则不做任何事情,它起作用,但仅在首页加载。我的意思是,如果我在粘性导航处活跃时调整窗口大小,即使我调整了720px以下的窗口大小,它仍然保持活动状态。这是jQuery:
//Sticky Navi
jQuery(function($) {
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = $('.main-navigation').offset().top;
var browserWidth = $( window ).width();
// our function that decides weather the navigation bar should have "fixed" css position or not.
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop(); // our current vertical position from the top
// 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_top > sticky_navigation_offset_top && browserWidth > 720) {
$('.main-navigation').css({ 'position': 'fixed', 'top':0, 'z-index':999999, 'opacity': 0.9, 'box-shadow': '0px 3px 5px #393939' })
} else {
$('.main-navigation').css({ 'position': 'relative', 'opacity': 1, 'box-shadow': 'none' });
}
};
// run our function on load
sticky_navigation();
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation();
});
});
感谢您的帮助
就像我在评论中所说的那样,没有您的HTML和CSS,我做不到太多,但这是有效的东西。您有一个怪异的功能需要修复。
function sticky_navigation() {
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = $('.main-navigation').offset().top;
var browserWidth = $(window).width();
var scroll_top = $(window).scrollTop(); // our current vertical position from the top
// 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_top > $('.main-navigation').height()) && (browserWidth > 720)) {
$('.main-navigation').css({ 'position': 'fixed', 'top':0, 'z-index':999999, 'opacity': 0.9, 'box-shadow': '0px 3px 5px #393939' });
} else {
$('.main-navigation').css({ 'position': 'relative', 'opacity': 1, 'box-shadow': 'none' });
}
};
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation();
});
带垃圾html的小提琴:http://jsfiddle.net/cm4t6/