百科右侧导航条的 js实现
时间: 2023-06-27 20:01:43 浏览: 60
百度百科右侧导航条的 js 实现主要包括以下几个方面:
1. 使用 position: fixed 实现固定在页面右侧位置;
2. 使用 JavaScript 监听滚动事件,根据滚动位置判断显示/隐藏状态;
3. 使用 JavaScript 动态改变导航条的样式和内容。
具体实现步骤如下:
1. 在 HTML 中添加导航条的代码,包括导航项的链接和图标等;
2. 使用 CSS 给导航条设置样式,包括位置、大小、颜色、背景等;
3. 使用 JavaScript 监听页面滚动事件,根据页面滚动位置计算导航条的显示/隐藏状态;
4. 使用 JavaScript 修改导航条的样式和内容,包括当前选中项的样式、滚动到指定位置的动画效果等。
以下是示例代码:
HTML 代码:
```html
<div class="nav">
<a href="#section1"><i class="icon1"></i> Section 1</a>
<a href="#section2"><i class="icon2"></i> Section 2</a>
<a href="#section3"><i class="icon3"></i> Section 3</a>
</div>
```
CSS 代码:
```css
.nav {
position: fixed;
top: 50%;
right: 0;
transform: translateY(-50%);
}
.nav a {
display: block;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
color: #666;
background: #fff;
border: 1px solid #ccc;
border-radius: 50%;
margin-bottom: 20px;
transition: all 0.3s;
}
.nav a:hover {
color: #fff;
background: #333;
border-color: #333;
}
.nav a.active {
color: #fff;
background: #333;
border-color: #333;
}
```
JavaScript 代码:
```javascript
var nav = document.querySelector('.nav');
var links = nav.querySelectorAll('a');
var sections = [];
links.forEach(function(link) {
var section = document.querySelector(link.getAttribute('href'));
sections.push(section);
});
window.addEventListener('scroll', function() {
var currentSectionIndex = 0;
sections.forEach(function(section, index) {
if (section.offsetTop - window.innerHeight / 2 <= window.scrollY) {
currentSectionIndex = index;
}
});
links.forEach(function(link, index) {
if (index === currentSectionIndex) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
});
```
以上代码实现了一个简单的固定在页面右侧的导航条,可以根据页面滚动位置自动高亮当前所在的部分。你可以根据需要修改样式和代码逻辑,实现更复杂的功能。