-1

我遇到了一个问题,我无法在向下滚动页面时使用此代码修复粘性导航。

我希望 js 不做任何事情如果浏览器窗口宽度低于 720 像素,它可以工作,但仅在第一页加载时有效。我的意思是,如果我在粘性导航处于活动状态时调整窗口大小,即使我在 720 像素以下调整窗口大小,它仍然保持活动状态。这是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();
  });

});

谢谢你的帮助

4

1 回答 1

1

就像我在评论中所说的那样,没有你的 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();
});

摆弄垃圾 HT​​ML:http: //jsfiddle.net/cm4t6/

于 2012-11-01T15:40:43.580 回答