,js实现页面滚动切换导航栏/点击导航栏跳转到指定位置...
时间: 2023-11-16 07:05:45 浏览: 197
1. 页面滚动切换导航栏
HTML结构:
```
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
<li><a href="#section4">Section 4</a></li>
</ul>
</nav>
<section id="section1">Section 1</section>
<section id="section2">Section 2</section>
<section id="section3">Section 3</section>
<section id="section4">Section 4</section>
```
CSS样式:
```
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #fff;
z-index: 999;
}
nav ul {
display: flex;
justify-content: center;
align-items: center;
height: 50px;
}
nav li {
margin: 0 20px;
}
nav a {
color: #333;
text-decoration: none;
font-size: 16px;
}
nav a.active {
color: #009688;
border-bottom: 2px solid #009688;
}
section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 32px;
}
```
JS代码:
```
// 获取所有导航链接和对应的section
const navLinks = document.querySelectorAll('nav a');
const sections = document.querySelectorAll('section');
// 监听页面滚动事件
window.addEventListener('scroll', () => {
let currentSection = '';
// 遍历每个section,判断当前滚动位置在哪个section内
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - sectionHeight / 3) {
currentSection = section.getAttribute('id');
}
});
// 遍历所有导航链接,给当前所在的section对应的导航链接添加active类名,其他移除
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href').includes(currentSection)) {
link.classList.add('active');
}
});
});
```
2. 点击导航栏跳转到指定位置
HTML结构:
```
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
<li><a href="#section4">Section 4</a></li>
</ul>
</nav>
<section id="section1">Section 1</section>
<section id="section2">Section 2</section>
<section id="section3">Section 3</section>
<section id="section4">Section 4</section>
```
CSS样式同上。
JS代码:
```
// 获取所有导航链接
const navLinks = document.querySelectorAll('nav a');
// 监听所有导航链接的点击事件
navLinks.forEach(link => {
link.addEventListener('click', event => {
event.preventDefault(); // 阻止默认跳转行为
const targetId = link.getAttribute('href'); // 获取目标section的id
const targetPosition = document.querySelector(targetId).offsetTop; // 获取目标section的相对页面顶部的距离
const startPosition = window.pageYOffset; // 获取当前滚动位置
const distance = targetPosition - startPosition; // 计算需要滚动的距离
const duration = 1000; // 滚动时间
let start = null; // 动画开始时间
// 动画函数,利用requestAnimationFrame实现平滑滚动效果
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const percentage = Math.min(progress / duration, 1);
window.scrollTo(0, startPosition + distance * percentage);
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
// 开始动画
window.requestAnimationFrame(step);
});
});
```
阅读全文