页面滚动的时候自动切换导航栏

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>href</title>
<style>
.left {
position: fixed;
width: 100px;
}
 
.right {
position: absolute;
left: 150px;
top: 0;
}
 
.active {
color: chocolate;
}
</style>
</head>

<body>
<div class="left">
<div>
<a href="#part1" id="part11">part1</a>
</div>
<div>
<a href="#part2" id="part12">part2</a>
</div>
<div>
<a href="#part3" id="part13">part3</a>
</div>
<div>
<a href="#part4" id="part14">part4</a>
</div>
<div>
<a href="#part5" id="part15">part5</a>
</div>
</div>
<div class="right">
<div id="part1" style="background:pink;width:100px;height:300px">11</div>
<div id="part2" style="background:gray;width:100px;height:700px">22</div>
<div id="part3" style="background:yellow;width:100px;height:700px">33</div>
<div id="part4" style="background:green;width:100px;height:900px">44</div>
<div id="part5" style="background:blue;width:100px;height:1000px">55</div>
</div>
<script src="./jquery-1.11.3.min.js"></script>
<script>
$(function() {

$(window).scroll(function() {
//为页面添加页面滚动监听事件
var wst = $(window).scrollTop() //滚动条距离顶端值
console.log("滚动条距离顶端值:" + wst)
var len = 6;
for (i = 1; i < len; i++) { //加循环
console.log("item距离顶端值:" + $("#part" + i).offset().top);

var next = i + 1;
var itemOffsetTop = $("#part" + i).offset().top;

console.log(i);
if (i === (len - 1)) {
var condition = itemOffsetTop <= wst;
} else {
var itemNextOffsetTop = $("#part" + next).offset().top;
var condition = itemOffsetTop <= wst && itemNextOffsetTop >= wst;
}
if (condition) { //判断滚动条位置
$('a').removeClass("active"); //清除c类
$("#part1" + i).addClass("active"); //给当前导航加c类
}
}

})
$('#nav a').click(function() {
$('#nav a').removeClass("c");
$(this).addClass("c");
});
});
</script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/maochunyan/p/9548466.html