什么叫电梯导航?顾名思义像我们做电梯一样,每个电梯按钮对应相应的楼层,在网页设计中电梯导航也被称为锚点导航。比如一个篇幅很长的页面,页面左侧有一个固定导航栏,页面内容分为多个部分(例如Section 1、Section 2、Section 3等)。当点击锚点元素时,页面内相应标记的元素会滚动到视口,同时页面内元素滚动时,相应的锚点也会高亮,上代码举例说明:
html部分:
nav id="navbar">
<ul>
<li><a href="#section1" class="nav-link">Section 1</a></li>
<li><a href="#section2" class="nav-link">Section 2</a></li>
<li><a href="#section3" class="nav-link">Section 3</a></li>
<li><a href="#section4" class="nav-link">Section 4</a></li>
</ul>
</nav>
<div id="section1" class="section">Section 1</div>
<div id="section2" class="section">Section 2</div>
<div id="section3" class="section">Section 3</div>
<div id="section4" class="section">Section 4</div>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
scroll-behavior: smooth;
}
#navbar {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
z-index: 1000;
}
#navbar ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
}
#navbar li {
margin: 0 15px;
}
#navbar a {
color: white;
text-decoration: none;
padding: 10px 15px;
display: inline-block;
}
#navbar a.active {
background-color: #555;
}
.section {
height: 500px;
padding: 20px;
border: 1px solid #ccc;
margin: 10px 0;
text-align: center;
line-height: 500px;
font-size: 2em;
}
js:
document.addEventListener("DOMContentLoaded", () => {
const navLinks = document.querySelectorAll(".nav-link");
// 添加点击事件,实现平滑滚动
navLinks.forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const targetId = link.getAttribute("href");
const targetElement = document.querySelector(targetId);
if (targetElement) {
targetElement.scrollIntoView({ behavior: "smooth" });
}
});
});
// 监听滚动事件,高亮当前导航项
window.addEventListener("scroll", () => {
let current = "";
navLinks.forEach((link) => {
const section = document.querySelector(link.hash);
if (section) {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - sectionHeight / 3) {
current = link.hash;
}
}
});
navLinks.forEach((link) => {
link.classList.remove("active");
if (link.hash === current) {
link.classList.add("active");
}
});
});
});
-
HTML部分:
- 导航栏由
<nav>
标签包裹,每个导航项是一个<a>
标签,href
属性指向对应的内容区块。 - 每个内容区块用
<div>
标签表示,id
与导航链接的href
对应。
- 导航栏由
-
CSS部分:
- 设置导航栏固定在页面顶部,内容区块有一定高度以便滚动。
- 为激活状态的导航链接添加样式(如背景色变化)。
-
JavaScript部分:
- 平滑滚动:通过
scrollIntoView
方法实现平滑滚动效果。 - 高亮当前导航项:监听
scroll
事件,根据页面滚动位置判断当前处于哪个区块,并为对应的导航链接添加active
类。
- 平滑滚动:通过