当前,我正在网站的导航栏中,我的JavaScript代码有问题。我在导航上使用了scroll-spy功能,并使用了Java脚本进行平滑滚动。另外,当滚动到网站的下一部分时,我希望导航-项目(链接)的背景色发生变化。我开发了一个合适的代码,但是它不起作用-它实际上什么也没做。
scroll_navbar {
position: fixed;
width: 14%;
height: 100vh;
z-index: 3;
padding: 0;
padding-left: 1%;
}
.nav-item {
background-color: rgba(255,255,255,0.6)!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item :hover {
background-color: rgba(255,255,255,1)!important;
color: rgb(0,0,0);
}
body {
position: relative;
}
.active {
background-color: rgba(255,255,255,1)!important;
}
.nav-link {
color: #000000;
}
.nav-item.scrolled {
background-color: rgba(249,71,108,0.6)!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item .scrolled :hover {
background-color: rgba(249,71,108,1) !important;
color: rgb(0,0,0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container d-flex align-items-center" id="scroll_navbar">
<div class="row">
<div class="col" style="padding: 0;">
<div id="spy">
<ul class="nav flex-column">
<li class="nav-item"><a href="#part1" class="nav-link">home</a></li>
<li class="nav-item"><a href="#part2" class="nav-link">about</a></li>
<li class="nav-item"><a href="#part3" class="nav-link">price</a></li>
<li class="nav-item"><a href="#part4" class="nav-link">contact</a></li>
</ul>
</div>
</div>
</div>
</div>
<script>
$(function () {
$(window).scroll(function () {
var $nav = $('.nav-item');
$nav.toggleClass('scrolled', $(this).scrollTop() >
$nav.height());
});
});
</script>
<script> $('body').scrollspy({ target: '#spy'}) </script>
<script src="smooth-scroll.js"></script>
<script>
var scroll = new SmoothScroll('a[href*="#"]');
</script>
您能找到更好的解决方案来更改链接(导航项)的背景颜色吗?
答案 0 :(得分:0)
我认为您的问题应该更清楚。您忘记了在CSS .nav-item a
中写链接标记。非常简单地检查一下。
scroll_navbar {
position: fixed;
width: 14%;
height: 100vh;
z-index: 3;
padding: 0;
padding-left: 1%;
}
.nav-item a {
color:white;
background-color: grey!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item :hover {
background-color: rgba(255,255,255,1)!important;
color: rgb(0,0,0);
}
body {
position: relative;
}
.active {
background-color: rgba(255,255,255,1)!important;
}
.nav-link {
color: #000000;
}
.nav-item.scrolled {
background-color: rgba(249,71,108,0.6)!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item .scrolled :hover {
background-color: rgba(249,71,108,1) !important;
color: rgb(0,0,0);
}
<div class="container d-flex align-items-center" id="scroll_navbar">
<div class="row">
<div class="col" style="padding: 0;">
<div id="spy">
<ul class="nav flex-column">
<li class="nav-item"><a href="#part1" class="nav-link">home</a></li>
<li class="nav-item"><a href="#part2" class="nav-link">about</a></li>
<li class="nav-item"><a href="#part3" class="nav-link">price</a></li>
<li class="nav-item"><a href="#part4" class="nav-link">contact</a></li>
</ul>
</div>
</div>
</div>