结构
HTML5
<div class="wrap">
<main class="cont">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</main>
<nav class="nav">
<span class="iconfont icon-home1 link active"></span>
<span class="iconfont icon-htm link"></span>
<span class="iconfont icon-css link"></span>
<span class="iconfont icon-js link"></span>
<span class="iconfont icon-xiangyingshi link"></span>
<span class="iconfont icon-ToDo-List link"></span>
</nav>
</div>
样式
CSS3
@import url(//at.alicdn.com/t/c/font_3859342_3uwkhw73sh3.css);
@import url(../../css/fonts_Inconsolata.css);
:root {
--main-color: #fe6ea1;
--w: 800px;
--offset: calc(var(--w));
--p-m-g: 10px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Inconsolata', sans-serif;
}
li {
list-style: none;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.wrap {
display: flex;
width: 96%;
max-width: var(--w);
aspect-ratio: 16/9;
}
.nav {
flex-basis: 80px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: var(--p-m-g);
background-color: var(--seconde-color);
}
.iconfont {
display: flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
font-size: 24px;
border-radius: 50%;
transition: 0.5s;
cursor: pointer;
}
main {
flex: 1;
height: 100%;
overflow: hidden;
background-color: #fffbfc;
}
.item {
display: grid;
align-content: flex-start;
gap: var(--p-m-g);
height: 100%;
padding: var(--p-m-g);
overflow-y: auto;
}
.item::-webkit-scrollbar {
width: 6px;
}
.item::-webkit-scrollbar-thumb {
background-color: var(--main-color);
}
.iconfont.active {
color: #fff;
background-color: var(--main-color);
box-shadow: 0 0 0px 6px #fe6ea166;
}
ol {
counter-reset: li-sn;
}
ol li {
counter-increment: li-sn;
}
ol li::before {
content: counter(li-sn);
color: #fff;
margin-right: 1em;
padding: 0 4px;
background-color: var(--main-color);
}
ul li::before {
content: '\e8af';
font-family: 'iconfont';
color: var(--main-color);
}
逻辑
JavaScript
- 获取元素 - 导航 .link 和内容 .item
- 遍历导航,添加事件侦听器 - 单击 click
- 单击时,对应的内容进入视图 - scrollIntoView()
- 先遍历移除活动类 .active
- 再为当前导航添加活动类 .active
const links = document.querySelectorAll('.link')
const items = document.querySelectorAll('.item')
links.forEach((link, ind) => {
link.addEventListener('click', () => {
items[ind].scrollIntoView({ behavior: 'smooth', block: 'center' })
links.forEach(link => link.classList.remove('active'))
link.classList.add('active')
})
})