我对web-dev相当新,我试图在滚动时将背景颜色从透明变为蓝色。我正在使用bootstrap。我尝试使用此JavaScript代码,但它无法正常工作
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('#startchange');
var offset = startchange.offset();
if (startchange.length){
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$("nav.navbar div.container-fluid").css('background-color', '#f0f0f0');
} else {
$("nav.navbar div.container-fluid").css('background-color', 'transparent');
}
});
}
这是我正在使用的HTML代码
<nav class="navbar" data-spy="affix">
<div class="container-fluid">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><img src="images/rubix-logo-navy.png"></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#about">About</a></li>
<li><a href="#team">Team</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
</div>
</nav>
这是CSS
nav.navbar {
margin: 0;
left: 0;
right: 0;
position: fixed;
top: -100%;
border-radius: 0;
transition: 300ms;
-webkit-transition: 300ms;
border: none; }
@media screen and (max-width: 767px) {
nav.navbar {
position: static;
top: 0;
} }
nav.navbar div.container-fluid {
background-color: transparent; }
nav.navbar button.navbar-toggle span.icon-bar {
color: #002776;
border-color: #002776;
background-color: #002776; }
nav.navbar a.navbar-brand {
color: #002776;
font-weight: 700;
font-size: 22px;
padding-top: 20px;
padding-bottom: 20px; }
nav.navbar a.navbar-brand img {
width: 125px; }
@media screen and (max-width: 767px) {
nav.navbar a.navbar-brand {
padding-top: 7px;
padding-bottom: 7px;
font-size: 16px; } }
nav.navbar ul.nav li a {
color: #002776;
transition: 300ms;
-webkit-transition: 300ms;
line-height: 24px;
font-size: 22px;
padding-top: 25px;
padding-bottom: 25px; }
nav.navbar ul.nav li a:hover {
color: #00a1de;
background-color: transparent; }
@media screen and (min-width: 768px) {
nav.navbar.affix {
position: fixed;
top: 0;
z-index: 100; } }
nav.navbar div.container-fluid.top-nav-collapse {
padding: 0;
border-bottom: 1px solid rgba(255,255,255,.3);
background: #000;
}
帮助将不胜感激
答案 0 :(得分:0)
根据我的理解,您想在向下滚动时更改导航背景,并在滚动到顶部时将其更改回来?如果我是正确的,那么这可能是你想要的编辑。
$(document).ready(function(){
var scroll_start = 0;
var offset = $("body").offset();
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$("nav.navbar div.container-fluid").css('background-color', '#f0f0f0');
} else {
$("nav.navbar div.container-fluid").css('background-color', 'transparent');
}
});
});