<div style="height: 200px"></div>
<nav class="sticky-nav">
<ul>
<li><a href="#sec1" class="smooth-scroll">Section1</a></li>
<li><a href="#sec2" class="smooth-scroll">Section2</a></li>
<li><a href="#sec3" class="smooth-scroll">Section3</a></li>
<li><a href="#sec4" class="smooth-scroll">Section4</a></li>
<li><a href="#sec5" class="smooth-scroll">Section5</a></li>
</ul>
</nav>
<section id="sec1">
<p class="text-center">Section1</p>
<div class="spacer"></div>
</section>
<section id="sec2">
<p class="text-center">Section2</p>
<div class="spacer"></div>
</section>
<section id="sec3">
<p class="text-center">Section3</p>
<div class="spacer"></div>
</section>
<section id="sec4">
<p class="text-center">Section4</p>
<div class="spacer"></div>
</section>
<section id="sec5">
<p class="text-center">Section5</p>
<div class="spacer"></div>
</section>
.sticky-nav {
width: 600px;
height: 50px;
margin: 0 auto;
}
.sticky-nav ul {
display: flex;
width: 600px;
height: 50px;
top: -50px;
margin: 0 auto;
background: #333;
transition: height 0.3s;
}
.sticky-nav ul.is-sticky {
position: fixed;
top: 0;
left: 0;
right: 0;
transition: top 0.3s;
}
.sticky-nav li {
width: 20%;
height: 100%;
}
.smooth-scroll {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
padding: 12px;
color: #fff;
}
.sticky-nav {
width: 600px;
height: 50px;
margin: 0 auto;
& ul {
display: flex;
width: 600px;
height: 50px;
top: -50px;
margin: 0 auto;
background: $color_main;
transition: height $speed_fast;
&.is-sticky {
position: fixed;
// top: -50px;
top: 0;
left: 0;
right: 0;
transition: top $speed_fast;
}
}
& li {
width: 20%;
height: 100%;
}
}
(function() {
const target = document.querySelector('.sticky-nav');
if(!target) {return;}
const fixTarget = target.querySelector('ul');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const rect = entry.target.getBoundingClientRect();
if(rect.bottom < 0) {
fixTarget.classList.add('is-sticky');
} else {
fixTarget.classList.remove('is-sticky');
}
});
});
observer.observe(target);
}());