【问题标题】:Issue with jQuery Sticky Nav and responsive designjQuery Sticky Nav 和响应式设计的问题
【发布时间】:2012-11-01 15:09:28
【问题描述】:

我遇到了一个问题,我无法用这段代码解决我在向下滚动页面时用来实现粘性导航的代码。

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

});

感谢您的帮助

【问题讨论】:

  • 没有你的 HTML 和 CSS 就不能做很多事情。
  • 我看不出 html 和 css 与该问题有何关联。该脚本有效我只需要知道当窗口在特定宽度下调整大小时如何在 jQuery 中卸载/禁用该函数。
  • HTML 和 CSS 始终与更改元素的 HTML 和 CSS 的任何 javascript 或 jquery 相关。

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


【解决方案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/

【讨论】:

  • 感谢您的帮助,它的工作方式与以前相同。如果我在滚动页面时调整窗口大小,它也会影响移动视图(我不希望这样)。我不是 jQuery 专家,但我想我需要一些东西来检查脚本加载后是否调整了窗口大小。
  • 因为您只在窗口滚动时调用该函数。如果你想在窗口调整大小时调用该函数,你需要在 .resize() 触发器中添加一个钩子。
  • 我已经设法让它最终工作了。一个主要问题是由另一个 jQuery 插件(处理小菜单)引起的,该插件更改了导航类名称。在该脚本之前加载脚本并添加 .resize() 触发器解决了该问题。谢谢 Ghlitch。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多