所以這個(gè)js代碼負(fù)責(zé)突出顯示滾動(dòng)條上的菜單,但是它不起作用。 我不知道是什么問(wèn)題,還有一個(gè)問(wèn)題是,當(dāng)我嘗試console.log(pageXOffset)或console.log(sectionLeft)時(shí),它們都沒(méi)有向控制臺(tái)記錄任何值,并且當(dāng)我滾動(dòng)時(shí)什么也沒(méi)有發(fā)生,這不是實(shí)際代碼的一部分,但我只是想獲得這些值,并查看它們?cè)跐L動(dòng)時(shí)如何變化。
<script>
const sections = document.querySelectorAll('section');
const navLi = document.getElementsByClassName('navbarItem');
window.addEventListener('scroll', function (){
changeOnScroll()
});
function changeOnScroll(){
let currentx=""
console.log(pageXOffset)
for( i = 0; i < sections.length; i++){
const sectionLeft = sections[i].offsetLeft;
console.log(sectionLeft)
const sectionWidth = sections[i].clientWidth;
if( pageXOffset >= sections[i].offsetLeft ){
currentx = sections[i].getAttribute('id');
}
}
for(var i = 0; i < navLi.length; i++){
navbarItem[i].classList.remove('active');
if(currentx = sections[i]){
navbarItem[i].classList.add('active')
}
}
}
</script>
</head>
<body>
<header>
<nav id="navbar">
<ul id="navbarlist">
<li class="navbarItem home"><a href="#home">home</a></li>
<li class="navbarItem about"><a href="#about">about</a></li>
<li class="navbarItem products"><a href="#products">products</a></li>
<li class="navbarItem services"><a href="#services">services</a></li>
<li class="navbarItem contactus"><a href="#contactus">contact us</a></li>
</ul>
</nav>
</header>
<main>
<div class="outer-wrapper">
<div class="inner-wrapper">
<section class="sections" id="home">
</section>
<section class="sections" id="about">
</section>
<section class="sections" id="products">
</section>
<section class="sections" id="services">
</section>
<section class="sections" id="contactus">
</section>
這是我的css:
#navbar{
position: absolute;
width: 50vw;
left: calc(50vw - 25vw);
}
#navbarlist{
top: 50px;
left: 25vw;
width: 50vw;
position: fixed;
display: flex;
justify-content: space-between;
z-index: 1;
padding: 0;
}
.navbarItem{
display: flex;
justify-content: center;
align-items: center;
color: #000;
opacity: 0.5;
width: 100px;
height: 100px;
border-radius: 50%;
}
.navbarItem:hover{
transform: scale(1.5);
margin-top: 30px;
}
.current{
transform: scale(1.3);
margin-top: 10px;
color: aqua;
}
.currentx{
transform: scale(1.3);
margin-top: 10px;
color: aqua;
}
.active{
transform: scale(1.3);
margin-top: 10px;
color: aqua;
}
.sections{
width: 100vw;
}