2017-02-19 29 views
0

我使用jQuery在滚动后更改Bootstrap导航栏的CSS元素。我的问题是,如果你的页面的顶部之后的任意位置加载页面,菜单将不会直到你向下滚动变得更小 - 使用下面的代码:如果不在页面顶部,用jQuery更改CSS

var a = $(".nav").offset().top; 

$(document).scroll(function(){ 
    if($(this).scrollTop() > a) 
    { 
     $('.navbar-fixed-top').css({"background":"#fff"}); 
     $('.navbar-fixed-top').css({"transition":"0.5s"}); 
     $('.navbar-fixed-top li a').css({"padding-top":"20px"}); 
     $('.navbar-fixed-top li a').css({"padding-bottom":"20px"}); 
    } else { 
     $('.navbar-fixed-top').css({"background":"transparent"}); 
     $('.navbar-fixed-top').css({"transition":"0.5s"}); 
     $('.navbar-fixed-top li a').css({"padding-top":"40px"}); 
     $('.navbar-fixed-top li a').css({"padding-bottom":"40px"}); 
    } 
}); 

我一直在试图改变这样如果它不在页面的顶部,它将执行scrollTop代码,但没有运气。

+0

这听起来像你可能正在寻找[一种方法来检查页面上的位置在jQuery](http://stackoverflow.com/a/17441121/2341603)。 –

回答

0

你的功能只作为事件侦听器运行,所以你必须首先手动运行它。试试这个代码:

var a = $(".nav").offset().top; 

function scrollListener(){ 
    if($(document).scrollTop() > a) 
    { 
     $('.navbar-fixed-top').css({"background":"#fff"}); 
     $('.navbar-fixed-top').css({"transition":"0.5s"}); 
     $('.navbar-fixed-top li a').css({"padding-top":"20px"}); 
     $('.navbar-fixed-top li a').css({"padding-bottom":"20px"}); 
    } else { 
     $('.navbar-fixed-top').css({"background":"transparent"}); 
     $('.navbar-fixed-top').css({"transition":"0.5s"}); 
     $('.navbar-fixed-top li a').css({"padding-top":"40px"}); 
     $('.navbar-fixed-top li a').css({"padding-bottom":"40px"}); 
    } 
}; 

$(document).scroll(scrollListener); 

scrollListener(); 
+0

不幸的是,这不起作用。它加载的应该只是在顶部。只有当您向下滚动时才会发生变化 - 但是当您上升时,超过您加载的点将返回到上一个菜单。 –

+0

也许,菜单总是比较小,而且如果它触摸顶部就会变得更大,这会更好吗? –

+0

你能提供在线演示吗? –

0

基本上,您需要对scrollload事件都运行调整功能。 下面是一个例子:

(function($) { 
    var a = $(".nav").offset().top; 

    var adjust = function() { 
     if($(document).scrollTop() > a) { 
      $('.navbar-fixed-top').css({"background":"#fff"}); 
      $('.navbar-fixed-top').css({"transition":"0.5s"}); 
      $('.navbar-fixed-top li a').css({"padding-top":"20px"}); 
      $('.navbar-fixed-top li a').css({"padding-bottom":"20px"}); 
     } else { 
      $('.navbar-fixed-top').css({"background":"transparent"}); 
      $('.navbar-fixed-top').css({"transition":"0.5s"}); 
      $('.navbar-fixed-top li a').css({"padding-top":"40px"}); 
      $('.navbar-fixed-top li a').css({"padding-bottom":"40px"}); 
     } 
    } 

    $(document).scroll(adjust); 
    $(function() { adjust; }) 
})(window.jQuery); 
+0

看看我的解决方案,你的版本不处理'$(this).scrollTop()' –

+0

这是完全相同的解决方案,我只是等待'window.load'事件触发并且不会污染全局名称空间... – motanelu

+0

尝试运行您的代码。事件订阅者有'this'指针指向被监听的元素(在这种情况下它是'document')。 正如我所看到的,你调用时没有任何指向'document'的指针,所以'this'指向'adjust'函数的实例。 您应该建议'$(function(){adjust.call(document);})'。 –