jquery实现侧边导航栏
时间: 2023-09-09 14:09:52 浏览: 89
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>
</ul>
</div>
<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>
```
CSS代码:
```
.sidebar {
position: fixed;
top: 50%;
left: 0;
transform: translateY(-50%);
}
.sidebar ul {
list-style: none;
padding: 0;
margin: 0;
}
.sidebar li {
margin-bottom: 10px;
}
.sidebar a {
display: block;
padding: 5px;
border-radius: 5px;
text-decoration: none;
color: #fff;
background-color: #333;
transition: background-color 0.3s ease;
}
.sidebar a:hover {
background-color: #555;
}
.section {
height: 500px;
margin-bottom: 50px;
}
```
jQuery代码:
```
$(document).ready(function() {
// 点击侧边导航栏,滚动到指定区域
$('.sidebar a').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 500);
});
// 监听滚动事件,高亮显示对应的导航栏
$(window).scroll(function() {
var sections = $('.section');
var positions = [];
sections.each(function() {
positions.push($(this).offset().top - 200);
});
var scrollTop = $(window).scrollTop();
var currentIndex = 0;
for (var i = 0; i < positions.length; i++) {
if (scrollTop >= positions[i]) {
currentIndex = i;
}
}
$('.sidebar a').removeClass('active');
$('.sidebar li').eq(currentIndex).find('a').addClass('active');
});
});
```
解释:
1. 点击侧边导航栏,通过`animate`函数实现页面滚动到指定区域;
2. 监听滚动事件,获取每个区域的位置信息,根据滚动位置计算出当前应该高亮显示的导航栏,并在对应的导航栏上加上`active`类名;
3. `active`类名对应的样式可以改变导航栏的背景色、字体颜色等,以突出显示当前所在的位置。
阅读全文