如何使用 CSS 和 JavaScript 创建粘性导航栏
[ CodePen 演示|原创文章]
粘性导航栏允许用户即使在向下滚动页面时也能访问网站的导航。
在这个例子中,我们将创建一个粘性导航栏,当导航固定时,它的尺寸也会缩小。
让我们开始创建 HTML:
<header id="header"></header>
<nav id="nav">
<ul>
<li><a href="#"><img src="https://img.icons8.com/color/96/000000/javascript.png" height="96" /></a></li>
<li><a href="#">Documentation</a></li>
<li><a href="#">Tutorials</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Community</a></li>
</ul>
<article>
<h1>Lorem Ipsum Dolor</h1>
<p>Consectetur adipiscing elit. Praesent vulputate elit felis, quis efficitur tortor viverra a. Quisque fermentum enim et enim imperdiet vestibulum at vitae tortor. Cras auctor scelerisque odio at varius. Nullam rhoncus nibh ut sem dignissim fringilla. Fusce dapibus nulla sed ipsum commodo molestie ut ut mauris.</p>
<!-- repeat as required -->
</article>
</nav>
接下来是 CSS:
#header {
height: 30vh;
background: url(https://images.pexels.com/photos/1089440/pexels-photo-1089440.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940);
background-size: cover;
}
#nav {
background-color: #000;
top: 0;
width: 100%;
}
#nav ul {
margin: 0;
padding: 0;
list-style: none;
display: flex;
}
#nav li {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
#nav ul li a {
color: #ffd600;
transition: all 0.4s;
}
#nav ul li img {
height: 96px;
transition: height 0.4s;
}
这将创建一个标题图像和全宽导航栏,其中每个元素<li>
均匀分布。
现在,JS 会检测 navbav 何时到达浏览器顶部并添加一个固定类:
const nav = document.querySelector('#nav');
let navTop = nav.offsetTop;
function fixedNav() {
if (window.scrollY >= navTop) {
nav.classList.add('fixed');
} else {
nav.classList.remove('fixed');
}
}
window.addEventListener('scroll', fixedNav);
最后,当导航栏激活固定类时的 CSS:
#nav.fixed {
position: fixed;
box-shadow: 5px 5px 19px 0px rgba(0, 0, 0, 0.5);
}
#nav.fixed ul li img {
height: 36px;
}
#nav.fixed ul li a {
font-size: 14px;
}
由于我们在<img>
和<a>
元素上有过渡,当应用固定类时,它们会平滑地缩放。
但这是可选的,因为您只需为粘性导航栏添加固定定位,而无需进行任何缩放。
文章来源:https://dev.to/michaelburrows/how-to-create-a-sticky-navbar-with-css-javascript-2bjj