javascript - HTML Hamburger - 如何形成正确的 X
问题描述
我正在尝试使用 css 构建一个动画汉堡包。为此,我使用了三种不同span
的点击动画——没什么特别的。
但是不知何故,变换原点被搞砸了,因此我无法形成正确的X
. 我该怎么做?
let active = false;
const handleNav = () => {
const hamburger = document.querySelector(".hamburger");
if (!active) {
hamburger.classList.add("is-active");
} else {
hamburger.classList.remove("is-active");
}
active = !active;
}
.hamburger {
width: 25px;
cursor: pointer;
}
span {
display: block;
width: 100%;
height: 2px;
background-color: black;
margin-bottom: 4px;
transform-origin: 0 50%;
transition: all 0.3s;
}
span:last-child {
margin-bottom: 0;
}
.is-active span:first-child {
transform: rotate(45deg);
}
.is-active span:nth-child(2) {
width: 0;
}
.is-active span:last-child {
transform: rotate(-45deg);
}
<div class="hamburger" onclick="handleNav()">
<span></span>
<span></span>
<span></span>
</div>
解决方案
一种方法是隐藏汉堡包并显示关闭图标。
另一种方法是计算制作完美关闭图标所需的宽度并在活动时设置宽度。这里宽度约为 17。请参见下面的代码。
let active = false;
const handleNav = () => {
const hamburger = document.querySelector(".hamburger");
if (!active) {
hamburger.classList.add("is-active");
} else {
hamburger.classList.remove("is-active");
}
active = !active;
}
.hamburger {
width: 25px;
cursor: pointer;
}
span {
display: block;
width: 100%;
height: 2px;
background-color: black;
margin-bottom: 4px;
transform-origin: 0 50%;
transition: all 0.3s;
}
span:last-child {
margin-bottom: 0;
}
.is-active span:first-child {
transform: rotate(45deg);
width: 17px
}
.is-active span:nth-child(2) {
width: 0;
}
.is-active span:last-child {
transform: rotate(-45deg);
width: 17px
}
<div class="hamburger" onclick="handleNav()">
<span></span>
<span></span>
<span></span>
</div>