汉堡菜单 CSS如何使用 CSS 和 JavaScript 创建汉堡菜单图标
最近,我投入了大量时间来提升我的前端技能,尤其是 CSS 和动画。俗话说,要想精通某件事,就必须大量练习。在制作作品集的时候,我需要一个汉堡菜单图标,因为我不想用市面上现有的图标,所以我决定自己做一个。
先决条件
您只需要掌握基本的 HTML、CSS 和 Javascript 知识。
编写 HTML
HTML 非常简单;我们有图标容器、菜单图标和嵌套在其中的三行。
<div class="container">
<div class="menu-icon">
<span class="line-1"></span>
<span class="line-2"></span>
<span class="line-3"></span>
</div>
</div>
页面的基本样式
这只是为了让图标居中并使一切看起来美观。
body {
background: #09182F;
}
.container {
width: 100%;
height: 80vh;
display: flex;
align-items: center;
justify-content: center;
}
菜单图标的样式
使用grid
,我们可以轻松地定位菜单图标和其中的嵌套行。place-items: center
是执行两项功能的瑞士军刀;align-items: center
和justify-items: center
。
.menu-icon {
display: grid;
place-items: center;
height: 55px;
width: 50px;
cursor: pointer;
}
为 3 条线添加样式
添加以下内容来设置嵌套行的样式。我们给第一行和第二行设置不同的宽度,以使图标看起来不那么传统。
.menu-icon {
...
& > span {
width: 50px;
height: 3px;
background: red;
display: block;
transition: all 0.3s ease-in-out;
}
}
.line-1 {
width: 42px;
justify-self: end;
}
.line-2 {
width: 35px;
justify-self: end;
}
悬停效果
在悬停效果上,我们改变了第一行和第二行的宽度。这种过渡使得宽度之间的切换流畅无缝。
.menu-icon {
...
&:hover span:nth-child(1) {
width: 35px;
}
&:hover span:nth-child(2) {
width: 40px;
}
}
单击图标时动画
有趣的部分来了。我们希望第一条线和第三条线在被点击时旋转形成一个 X,而第二条线则消失。
.menu-icon {
...
&.active span:nth-child(1) {
transform-origin: center center;
transform: rotate(-45deg) translate(-12px, 12px);
width: 55px;
}
&.active span:nth-child(2) {
transform: translateX(10px);
opacity: 0;
}
&.active span:nth-child(3) {
transform-origin: center center;
transform: rotate(45deg) translate(-15px, -14px);
width: 55px;
}
}
当menu-icon
单击时,active
将添加类,第一行和第二行lines
成为目标,我们使用rotate
&translate
属性来形成一个 X。此外,我们通过使用移动translateX
并将不透明度设置为 0 来隐藏第二行。
添加 JavaScript
剩下的就是添加一些 Js 来切换类active
。
const menuIcon = document.querySelector('.menu-icon');
function toggleMenuIcon() {
menuIcon.classList.toggle('active')
}
menuIcon.addEventListener('click', toggleMenuIcon);
好了,我们定制的汉堡菜单图标就完成了。最终效果如下。
如果您学到了新知识,请点赞并留下评论。
文章来源:https://dev.to/emmaadesile/how-to-create-a-hamburger-menu-icon-with-css-and-javascript-1kgd