<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 3000px;
}
.aside {
position: fixed;
left: 0;
top: 50%;
transform: translateY(-50%);
}
.item {
height: 40px;
line-height: 40px;
text-align: center;
padding: 0 10px;
cursor: pointer;
}
.active {
background-color: red;
color: #fff;
}
.content {
width: 660px;
margin: 400px auto;
}
.neirong {
height: 300px;
margin-bottom: 20px;
color: #fff;
}
.content1 {
background-color: red;
}
.content2 {
background-color: blue;
}
.content3 {
background-color: orange;
}
.content4 {
background-color: yellowgreen;
}
</style>
</head>
<body>
<div class="aside">
<div class="item active">男装/女装</div>
<div class="item">儿童服装/游乐园</div>
<div class="item">电子产品</div>
<div class="item">电影/美食</div>
</div>
<div class="content">
<div class="neirong content1">男装/女装</div>
<div class="neirong content2">儿童服装/游乐园</div>
<div class="neirong content3">电子产品</div>
<div class="neirong content4">电影/美食</div>
</div>
<script>
//1.获取事件源 item neirong
const item = document.querySelectorAll('.item')
const neirong = document.querySelectorAll('.neirong')
//2.注册事件
//由于是数组 先遍历数组
for (let i = 0; i < item.length; i++) {
//2.1侧边栏点击控制滑动页面
//注册item点击事件
item[i].addEventListener('click', function() {
//排他思想先移除 再添加
document.querySelector('.aside .active').classList.remove('active')
this.classList.add('active')
//在判断页面中滑动距离 scrollTop鼠标滑动距离 offsetTop盒子离浏览器顶部距离
document.documentElement.scrollTop = neirong[i].offsetTop
})
//2.2滑动页面滑动控制侧边栏菜单
//给window添加滑动事件
window.addEventListener('scroll', function() {
//由于在for循环遍历 可以得到neirong的小盒子索引号 通过用索引号来控制侧边栏菜单
if (document.documentElement.scrollTop >= neirong[i].offsetTop) {
// console.log(i) 此处i为neirong的小盒子滑动到相应位置会得到相应的索引号
// console.log(item[i]) 可以判断item每一项的内容
//排他思想
document.querySelector('.aside .active').classList.remove('active')
item[i].classList.add('active')
}
})
}
</script>
</body>
</html>
电梯滑动:
1.点击侧边栏控制中心内容滑动到相应内容(点击事件)
2.通过滑动中心内容,使对应的侧边栏得到相应的属性(滑动事件)