html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body .box {
width: 1200px;
}
body .box {
margin: 0 auto;
}
ul {
list-style: none;
}
body .box ul li {
height: 800px;
background-color: silver;
margin-bottom: 20px;
font-size: 30px;
font-weight: bold;
}
body .left {
position: fixed;
left: 20px;
bottom: 100px;
width: 100px;
height: 250px;
top: 50%;
margin-top: -125px;
background-color: silver;
}
body .left ul li {
height: 50px;
line-height: 50px;
text-align: center;
cursor: pointer;
}
body .current {
color: #fff;
background-color: tomato;
}
</style>
</head>
<body>
<div id="box" class="box">
<ul class="list">
<li class="content-part" data-n="栏目一">栏目一</li>
<li class="content-part" data-n="栏目二">栏目二</li>
<li class="content-part" data-n="栏目三">栏目三</li>
<li class="content-part" data-n="栏目四">栏目四</li>
<li class="content-part" data-n="栏目五">栏目五</li>
</ul>
</div>
<div class="left">
<ul id="left-list">
<li data-n="栏目一">栏目一</li>
<li data-n="栏目二">栏目二</li>
<li data-n="栏目三">栏目三</li>
<li data-n="栏目四">栏目四</li>
<li data-n="栏目五">栏目五</li>
</ul>
</div>
</body>
<script>
var oList = document.getElementById('left-list');
// 点击事件委托
oList.onclick = function (e) {
if (e.target.tagName.toLowerCase() == 'li') {
// 取data-n值
var n = e.target.getAttribute('data-n');
// []属性选择器
var contentPart = document.querySelector('.content-part[data-n=' + n + ']');
// 设置卷动
document.documentElement.scrollTop = contentPart.offsetTop;
}
}
// 页面卷动时,左侧盒子栏目背景随之变化
var contents = document.querySelectorAll('.content-part');
var lis = document.querySelectorAll('#left-list li');
var offsetTopArr = [];
for (var i = 0; i < contents.length; i++) {
offsetTopArr.push(contents[i].offsetTop);
}
// 为了方便比较,追加无穷大
offsetTopArr.push(Infinity);
// 监听卷动
var nowFloor = -1;
window.onscroll = function (e) {
var nowScrollTop = document.documentElement.scrollTop;
// break的i值即为盒子数组下标
for (var i = 0; i < offsetTopArr.length; i++) {
if (nowScrollTop >= offsetTopArr[i] && nowScrollTop < offsetTopArr[i + 1]) {
break;
}
}
// 楼层不等,进行样式更改
if (nowFloor != i) {
nowFloor = i;
for (var j = 0; j < lis.length; j++) {
if (j == i) {
// 当前楼层添加样式
lis[j].className = 'current';
} else {
// 去掉其他楼层的样式
lis[j].className = '';
}
}
}
}
</script>
</html>
实现效果