2017-02-17 80 views
0

如果我向下滚动到我的网站位置,如何更改CSS文件中的背景颜色?从Java脚本更改CSS内容

$(document).ready(function() { 
 
    var scroll_pos = 0; 
 
    $(document).scroll(function() { 
 
     scroll_pos = $(this).scrollTop(); 
 
     if (scroll_pos > 260) { 
 
      $('span[class="icon-bar"]').css('background-color', '#2CA8FF'); 
 
     } else { 
 
      $('span[class="icon-bar"]').css('background-color', 'white'); 
 
     } 
 
    }); 
 
});
.navbar - transparent.navbar - toggle.icon - bar, [class *= "navbar-ct"].navbar - toggle.icon - bar { 
 
    background - color: white!important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav class="navbar navbar-ct-blue navbar-transparent navbar-fixed-top" role="navigation"> 
 
    <div class="container"> 
 
     <!-- Brand and toggle get grouped for better mobile display --> 
 
     <div class="navbar-header"> 
 
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> 
 
       <span class="sr-only">Toggle navigation</span> 
 
       <span class="icon-bar"></span> 
 
       <span class="icon-bar"></span> 
 
       <span class="icon-bar"></span> 
 
      </button> 
 
     </div> 
 
    </div> 
 
</nav>

它与其他内容,如图片,而不是与此有关。为什么?

+0

我真的建议使用一个选择器,如$('nav .icon-bar')'或类似并保存到一个以避免让jQuery在每个'scroll'事件的整个'document'中搜索每个''。 –

+0

你为什么要在初始化静态颜色时尝试使用.navbar-transparent类?导航栏透明将有自己的引导CSS属性,可能会干扰您的自定义CSS。 –

回答

0

。这增加的特殊性,这可能会导致此:

.icon-bar { 
    background-color: white !important; 
} 

...压倒这样的:

$('span[class="icon-bar"]').css('background-color', '#2CA8FF'); 

您可以快速尝试删除!important,看看能否解决。

+0

感谢您的帮助。我现在不在,为什么我没有看到这^^ – Tom

0

更改代码:您使用在你的CSS文件中的!important声明

$('span.icon-bar').css('background-color', 'white'); 
0

是的,你在这里有一个针对你试图建立的样式的特异性问题(因为Bootstrap)。我已经多次完成了你想要的东西,通常我会在颜色改变后写完!最后

if(scroll_pos > 260) { 
    $('span.icon-bar').addClass('blue'); 
} else { 
    $('span.icon-bar').removeClass('blue'); 
} 

,你可以看到,我没有合作过:我用正常的解决方案是创建两个clases:

.blue { 
    background-color: #2CA8FF !important; 
} 

.white { 
    background-color: #FFF !important; 
} 

,然后在jQuery的分配类,而不是风格。白色。那是因为我直接给它分配给我的HTML元素:

<span class="icon-bar" class="white"></span> 
<span class="icon-bar" class="white"></span> 
<span class="icon-bar" class="white"></span> 

默认情况下,所有的都是白色的,然后,当你达到260,它们变成蓝色,因为它是最后一个指定的类。它会改变你的代码有点,但它已为我工作...