这是我参与8月更文挑战的第14天,活动详情查看:8月更文挑战
作者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权
背景
折叠导航栏动画:是指当我们点击 关闭按钮 时,导航栏自动折叠,再次 点击按钮 时,导航栏又自动展开的动画效果,这种效果顺畅,简单又自然,节约空间的同时又兼顾了美感,但因为有比其更优秀的替代方案—— 抽柜,所以这种效果并未被大企业广泛使用,但在 博客、个人页中使用,往往能起到意想不到的好效果。
最终效果
一、添加 HTML 文件
<nav class="active" id="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Works</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
<button class="icon" id="toggle">
<div class="line line1"></div>
<div class="line line2"></div>
</button>
</nav>
二、添加 CSS 文件
先初始化页面
- 设置
*为box-sizing: border-box - 设置
body来使整个项目居中
* {
box-sizing: border-box;
}
body {
background-color: #eafbff;
background-image: linear-gradient(
to bottom,
#eafbff 0%,
#eafbff 50%,
#5290f9 50%,
#5290f9 100%
);
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
主要的 CSS 代码
nav {
background-color: #fff;
padding: 20px;
width: 80px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 3px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
transition: width 0.6s linear;
overflow-x: hidden;
}
nav.active {
width: 350px;
}
nav ul {
display: flex;
list-style-type: none;
padding: 0;
margin: 0;
width: 0;
transition: width 0.6s linear;
}
nav.active ul {
width: 100%;
}
nav ul li {
transform: rotateY(0deg);
opacity: 0;
transition: transform 0.6s linear, opacity 0.6s linear;
}
nav.active ul li {
opacity: 1;
transform: rotateY(360deg);
}
nav ul a {
position: relative;
color: #000;
text-decoration: none;
margin: 0 10px;
}
.icon {
background-color: #fff;
border: 0;
cursor: pointer;
padding: 0;
position: relative;
height: 30px;
width: 30px;
}
.icon:focus {
outline: 0;
}
.icon .line {
background-color: #5290f9;
height: 2px;
width: 20px;
position: absolute;
top: 10px;
left: 5px;
transition: transform 0.6s linear;
}
.icon .line2 {
top: auto;
bottom: 10px;
}
nav.active .icon .line1 {
transform: rotate(-765deg) translateY(5.5px);
}
nav.active .icon .line2 {
transform: rotate(765deg) translateY(-5.5px);
}
三、添加 JS 文件
- 通过
document.getElementById('toggle'),获得toggle节点 - 通过
document.getElementById('nav'),获得nav节点 - 通过
addEventListener为toggle节点添加一个点击事件 - 当点击时,添加切换事件,展示或隐藏
nav节点的active类名
const toggle = document.getElementById('toggle')
const nav = document.getElementById('nav')
toggle.addEventListener('click', () => nav.classList.toggle('active'))
❤️ 感谢大家
如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。
如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。