- DEMO
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210110160230167.gif#pic_center)
- 代码写的不太好,大佬可以帮忙修改修改哈
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html {
scroll-behavior: smooth
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.item {
position: relative;
width: 100%;
font-size: 30px;
text-align: center;
height: 100vh;
line-height: 100px;
}
.tab-item {
cursor: pointer;
line-height: 100px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.black {
background-color: black;
color: white;
}
.yellow {
background-color: yellow;
}
.tab {
position: fixed;
width: 100px;
height: 400px;
background-color: white;
top: 30%;
right: 10px;
display: flex;
flex-direction: column;
justify-content: space-around;
text-align: center;
}
.show {
background-color: red;
}
.backTop {
cursor: pointer;
position: fixed;
right: 30px;
bottom: 30px;
display: none;
background-color: #ccc;
width: 100px;
line-height: 40px;
color: white;
animation: show .1s ease;
text-align: center;
z-index: 10;
}
@keyframes show {
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
</style>
<body>
<div class="backTop">回到顶部</div>
<div id="list">
<div class="item red">
楼区一
</div>
<div class="item blue">
楼区二
</div>
<div class="item black">
楼区三
</div>
<div class="item yellow">
楼区四
</div>
</div>
<div class="tab">
<div class="tab-item show">一层</div>
<div class="tab-item">二层</div>
<div class="tab-item">三层</div>
<div class="tab-item">四层</div>
</div>
<script>
var show = ['red', 'blue', 'black', 'yellow']
var tab_item = document.querySelectorAll('.tab-item')
var item = document.querySelectorAll('.item')
var flag = true
var backTop = document.querySelectorAll('.backTop')[0]
tab_item.forEach((item, index) => {
item.addEventListener('click', scrollColor, false)
item.index = index
});
function scrollColor() {
if (flag) {
flag = false
console.log(flag);
var way = item[this.index].offsetTop
var timer = setInterval(() => {
scrollTo(0, way)
for (var i = 0; i < item.length; i++) {
if (way == innerHeight * i) {
clearInterval(timer)
flag = true
}
}
}, 100);
}
}
document.onscroll = function () {
for (var i = 0; i < tab_item.length; i++) {
if (scrollY > innerHeight * i - 20) {
for (var j = 0; j < tab_item.length; j++) {
tab_item[j].style.backgroundColor = 'white'
tab_item[j].style.color = 'black'
}
tab_item[i].style.backgroundColor = show[i]
if (i === 2) {
tab_item[i].style.color = 'white'
}
}
}
if (scrollY > innerHeight) {
backTop.style.display = 'block'
} else {
backTop.style.display = 'none'
}
}
backTop.onclick = function () {
if (flag) {
flag = false
var timetop = setInterval(() => {
scrollTo(0, 0)
if (scrollY == 0) {
clearInterval(timetop)
flag = true
}
}, 300);
}
}
</script>
</body>
<html>