HTML代码
<div class="wrap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
<div class="floor">
<div>1楼</div>
<div>2楼</div>
<div>3楼</div>
<div>4楼</div>
<div>5楼</div>
<div>6楼</div>
<div>7楼</div>
</div>
CSS代码
*{margin: 0;padding: 0;}
.wrap div{
border:1px solid red;
width:600px;
height: 500px;
margin:20px auto;
}
.floor{
position: fixed;
right:0;
top:50%;
transform:translateY(-50%)
}
.floor div{
border-bottom:2px solid black;
line-height: 30px;
}
JS代码
var aDiv = document.querySelectorAll(".wrap div")
var floors = document.querySelectorAll(".floor div")
var html = document.documentElement
var arr = [] //存储所有内容div的距离文档顶部的值
var current=0 //当前所见的div的序号 current当前
for (var i = 0; i < aDiv.length; i++) {
arr.push(aDiv[i].offsetTop)//获取所有div的offsettop值
}//每一个div距离顶部的距离
console.log(arr)
window.οnscrοll=function(){ //onscroll在元素滚动条滚动式触发的事件
// console.log(html.scrollTop)
var s = html.scrollTop+window.innerHeight/2
//整个文档滚动时距离顶部的距离
for (var i = 0; i < arr.length; i++) {
if(s>arr[i]&&s<arr[i+1]){
current = i
}
if(s>arr[arr.length-1]){
current=arr.length-1
}//到最后一楼
}
for (var i = 0; i < aDiv.length; i++) {
floors[i].style.color="black"
}
floors[current].style.color="red" //改变楼层文字的颜色
}
for (var i = 0; i < floors.length; i++) {
floors[i].index=i
floors[i].οnclick=function(){
html.scrollTo({
top:arr[this.index],
behavior:"smooth" //平滑
})
}
}
|
|