<body>
<nav>
<ul>
<li><a class="js-curnav-switch" href="#menu1">menu1</a></li>
<li><a class="js-curnav-switch" href="#menu2">menu2</a></li>
<li><a class="js-curnav-switch" href="#menu3">menu3</a></li>
<li><a class="js-curnav-switch" href="#menu4">menu4</a></li>
</ul>
</nav>
<main>
<section id="menu1">
content1
</section>
<section id="menu2">
content2
</section>
<section id="menu3">
content3
</section>
<section id="menu4">
content4
</section>
</main>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
nav {
width: 100%;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
background: rgba(0,0,0,.2);
ul {
display: flex;
justify-content: center;
a {
display: block;
margin: 0 10px;
line-height: 60px;
text-decoration: none;
color: #000;
font-weight: bold;
&.is-current {
color: #f00;
}
}
}
}
main {
padding-top: 60px;
}
section {
min-height: 400px;
padding: 20px;
text-align: center;
&:nth-child(1) { background: #fee; }
&:nth-child(2) { background: #efe; }
&:nth-child(3) { background: #eef; }
&:nth-child(4) { background: #fef; }
}
View Compiled
if($('a[href^="#"]').length){
$('a[href^="#"]').click(function() {
$('html,body').animate({ scrollTop: $($(this).attr('href')).offset().top -60 }, 'slow','swing');
return false;
});
}
function onePageNav( switchName ) {
const navSwitch = $(switchName);
const deductHeight = 60;
let navArr = [];
navSwitch.each(function(i){
let navSwitchHref = $(this).attr('href');
let tgtOff = $(navSwitchHref).offset().top - deductHeight;
navArr.push([]);
navArr[i].switch = $(this);
navArr[i].tgtOff = tgtOff;
});
// console.log(navArr);
$(window).scroll(function () {
for( let i = 0; i < navArr.length; i++ ){
let scroll = $(window).scrollTop();
let tgtKey = navArr[i];
let tgtSwitch = tgtKey.switch;
let tgtOff = tgtKey.tgtOff;
if ( scroll >= tgtOff ) {
navSwitch.removeClass('is-current');
tgtSwitch.addClass('is-current');
} else {
tgtSwitch.removeClass('is-current');
}
}
});
}
$(window).on('load resize',function(){
onePageNav('.js-curnav-switch');
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.