写一个侧边导航栏+滑动电梯效果
时间: 2023-10-30 21:06:16 浏览: 40
这里是一个简单的侧边导航栏滑动电梯效果的示例:
HTML代码:
```
<div class="sidebar">
<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>
<li><a href="#section5">Section 5</a></li>
</ul>
</div>
<div id="section1" class="section">
<h2>Section 1</h2>
<p>Content goes here</p>
</div>
<div id="section2" class="section">
<h2>Section 2</h2>
<p>Content goes here</p>
</div>
<div id="section3" class="section">
<h2>Section 3</h2>
<p>Content goes here</p>
</div>
<div id="section4" class="section">
<h2>Section 4</h2>
<p>Content goes here</p>
</div>
<div id="section5" class="section">
<h2>Section 5</h2>
<p>Content goes here</p>
</div>
```
CSS代码:
```
.sidebar {
position: fixed;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 100px;
background-color: #f1f1f1;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
margin: 10px 0;
}
a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
transition: background-color 0.3s ease;
}
a:hover {
background-color: #ccc;
}
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
}
```
JavaScript代码:
```
const sidebar = document.querySelector('.sidebar');
const sections = document.querySelectorAll('.section');
window.addEventListener('scroll', () => {
const currentSection = [...sections].findIndex((section) => section.getBoundingClientRect().top >= 0) - 1;
if (currentSection >= 0) {
const currentLink = sidebar.querySelector(`a[href="#${sections[currentSection].id}"]`);
const links = sidebar.querySelectorAll('a');
links.forEach((link) => link.classList.remove('active'));
currentLink.classList.add('active');
}
});
sidebar.addEventListener('click', (event) => {
event.preventDefault();
const target = event.target;
if (target.tagName === 'A') {
const link = target.getAttribute('href');
const section = document.querySelector(link);
section.scrollIntoView({ behavior: 'smooth' });
}
});
```
这个示例中,我们使用了CSS定位和盒模型来创建了一个固定在屏幕左侧的侧边导航栏,其中包含了一些链接,每个链接都指向了页面上的不同部分,这些部分都使用了一个共同的类名`.section`来标识。
在JavaScript中,我们使用了`window`对象上的`scroll`事件来监听页面的滚动,然后根据当前滚动位置来确定用户目前正在查看哪个部分。我们使用了`getBoundingClientRect()`方法来获取每个部分的位置,然后使用`findIndex()`方法来查找最接近顶部的部分索引。一旦我们找到了当前的部分,我们就可以在侧边导航栏中高亮显示相应的链接。
我们还监听了侧边导航栏上的`click`事件,以便能够响应用户点击导航链接的行为。当用户点击一个链接时,我们使用`getAttribute()`方法来获取链接的`href`属性,然后使用`querySelector()`方法来查找对应的部分。最后,我们使用`scrollIntoView()`方法来滚动到该部分并平滑进行动画。