简易效果图:
代码如下有详细的注释:
<title>固定侧边栏</title>
<style>
* {
padding: 0px;
margin: 0px;
}
.a {
width: 1400px;
height: 200px;
background-color: red;
text-align: center;
margin-top: 50px;
}
.b {
width: 1400px;
height: 300px;
background-color: rgb(198, 240, 46);
text-align: center;
}
.c {
width: 1400px;
height: 600px;
background-color: rgb(0, 255, 55);
text-align: center;
}
.d {
width: 1400px;
height: 400px;
background-color: rgb(212, 0, 255);
text-align: center;
}
.e {
position: absolute;
right: 69px;
top: 200px;
width: 50px;
height: 200px;
background-color: pink;
}
span {
position: absolute;
display: none;
width: 50px;
height: 50px;
background-color: pink;
top: 200px;
text-align: center;
cursor: pointer;
}
li {
list-style: none;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
cursor: pointer;
}
.color {
background-color: aquamarine;
}
</style>
<script src="../js/jQuery.js"></script>
</head>
<body>
<div class="a" id="div1">头部</div>
<div class="b">导航部</div>
<div class="c" id="div3">主体部</div>
<div class="d">尾部</div>
<div class="e" id="div5">
<ul>
<li>红色</li>
<li>黄色</li>
<li>绿色</li>
<li>紫色</li>
</ul>
<span>返回顶部</span>
</div>
</body>
</html>
<script>
var div1 = document.getElementById('div1');
var div3 = document.getElementById('div3');
var div5 = document.getElementById('div5');
var span = document.querySelector('span');
//固定之后 距离页面顶部的 top值
var div5top = div5.offsetTop - div1.offsetTop;
//页面滚动事件
document.addEventListener('scroll', function () {
if (window.pageYOffset >= div1.offsetTop) {
div5.style.position = 'fixed';
div5.style.top = div5top + 'px';
} else {
div5.style.position = 'absolute';
div5.style.top = '200px';
}
if (window.pageYOffset >= div3.offsetTop) {
span.style.display = 'block';
} else {
span.style.display = 'none';
}
})
//返回顶部
$('span').click(function () {
$('bodu,html').animate({
scrollTop: 0
})
});
var flag = true; //节流阀
//点击右边导航栏 左边进行滑动
$('#div5 ul li').click(function () {
flag = false;
$(this).addClass('color').siblings().removeClass('color');
// $(this).index(); 得到索引号
var juli = $('div').eq($(this).index()).offset().top;
$('body,html').animate({
scrollTop: juli
}, function () {
flag = true;
});
});
//页面滚动事件
$(window).scroll(function () {
if (flag) {
$('div').each(function (i, ele) { //遍历div //i是索引号 ele是元素
if ($(document).scrollTop() >= $(ele).offset().top - 5) { //如果 页面卷去距离大于等于div距离顶部的距离时
$('#div5 ul li').eq(i).addClass('color').siblings().removeClass('color');
}
});
}
});
</script>