<style>
* {
margin: 0;
padding: 0;
text-align: center;
font-size: 30px;
font-weight: 800;
list-style: none;
}
.nav {
width: 100%;
height: 60px;
background-color: #000;
}
.banner {
width: 1200px;
height: 800px;
background-color: pink;
margin: 0 auto;
line-height: 800px;
}
.content1 {
width: 1200px;
height: 500px;
background-color: orange;
margin: 0 auto;
line-height: 500px;
}
.content2 {
width: 1200px;
height: 500px;
background-color: aqua;
margin: 0 auto;
line-height: 500px;
}
.content3 {
width: 1200px;
height: 500px;
background-color: purple;
margin: 0 auto;
line-height: 500px;
}
.content4 {
width: 1200px;
height: 500px;
background-color: skyblue;
margin: 0 auto;
line-height: 500px;
}
.foot {
width: 100%;
height: 600px;
background-color: #000;
}
ul {
width: 100px;
position: fixed;
left: 200px;
top: 50%;
margin-top: -60px;
display: none;
}
li {
width: 100px;
height: 30px;
border: 1px solid #ccc;
box-sizing: border-box;
font-size: 16px;
font-weight: normal;
line-height: 30px;
}
</style>
</head>
<body>
<div class="nav"></div>
<div class="banner">banner</div>
<div class="content content1">content1</div>
<div class="content content2">content2</div>
<div class="content content3">content3</div>
<div class="content content4">content4</div>
<div class="foot"></div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
// 获取元素
var content = document.getElementsByClassName("content");
var list = document.getElementsByTagName("li");
var floor = document.getElementsByTagName("ul")[0];
console.log(content[0].offsetTop);
// 滚动,内容和楼层同步
document.body.onscroll = function () {
// 滚动距离
// console.log(document.documentElement.scrollTop);
var slength = window.pageYOffset;
// 内容边界
// if (slength < content[0].offsetTop) {
// floor.style.display = "none";
// } else if (slength < content[1].offsetTop) {
// floor.style.display = "block";
// siblingFun();
// list[0].style.backgroundColor = "red";
// } else if (slength < content[2].offsetTop) {
// siblingFun();
// list[1].style.backgroundColor = "red";
// } else if (slength < content[3].offsetTop) {
// siblingFun();
// list[2].style.backgroundColor = "red";
// } else {
// siblingFun();
// list[3].style.backgroundColor = "red";
// }
if (slength < content[0].offsetTop) {
floor.style.display = "none";
} else {
floor.style.display = "block";
for (var i = 0; i < content.length; i++) {
if (slength >= content[i].offsetTop) {
siblingFun();
list[i].style.backgroundColor = "red";
}
}
}
}
// 排他思想:干掉其他人,只留我自己
// 封装排他函数
function siblingFun() {
for (var i = 0; i < list.length; i++) {
list[i].style.backgroundColor = "#fff";
}
}
// 楼层点击和内容同步
for (var i = 0; i < list.length; i++) {
// 保留 i 值
list[i].index = i;
list[i].onclick = function () {
// 页面滚动距离 = content[i].offsetTop
// 事件中的 this 指向事件源
console.log(this);
document.documentElement.scrollTop = content[this.index].offsetTop;
}
}
</script>
</body>
楼层导航的实现
最新推荐文章于 2024-10-25 15:04:44 发布