我使用Angular 5和Bootstrap 4作为我的主要前端框架。我正在使用fixed-top
bootstrap的导航栏。我正在尝试在滚动窗口时更改导航栏的背景。这就是为什么我尝试使用jquery但我收到错误,即$ is not defined
。
这是我的jquery代码
$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
$(".navbar-fixed-top").css("background-color", "#ffffff");
} else {
$(".navbar-fixed-top").css("background-color", "transparent");
}
});
});
这是我的HTML代码
<nav class="navbar navbar-expand-lg fixed-top navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor03" aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor03">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
答案 0 :(得分:0)
如果您将$(".navbar-fixed-top")
替换为$(".navbar.fixed-top")
,那么您的代码就像下面的演示一样。
$ is not defined
。所以你必须再次检查你的angular-cli.json。
$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
// change the color from white to red to show the effect
$(".navbar.fixed-top").css("background-color", "red");
} else {
$(".navbar.fixed-top").css("background-color", "transparent");
}
});
});
&#13;
nav{
height: 200vh; /* increase the height to make it scrollable*/
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-lg fixed-top navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor03" aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor03">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
&#13;