jQuery Sticky Nav和响应式设计的问题

时间:2012-11-01 15:09:28

标签: jquery navigation responsive-design sticky browser-width

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

我希望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();
  });

});

感谢您的帮助

1 个答案:

答案 0 :(得分: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();
});

摆弄垃圾HTML:http://jsfiddle.net/cm4t6/

相关问题