我正在将鼠标悬停在absolute
位置上的汉堡菜单动画效果很好,但是我希望它能平滑。我尝试将过渡设置为跨度,但没有成功。这是我的代码。
const mainHeader = document.querySelector('#header');
const barOne = document.querySelector('.bar-1');
const barThree = document.querySelector('.bar-3');
mainHeader.addEventListener('mouseover', () => {
barOne.style.top = '6px';
barThree.style.top = '-6px';
})
#header {
position: fixed;
top: 5vh;
left: 50%;
transform: translateX(-50%);
z-index: 1;
cursor: pointer;
}
nav.menu span {
background: #3d3d3d;
width: 30px;
height: 1px;
display: block;
margin-bottom: 6px;
position: relative;
transition: all 1s;
}
<header id="header">
<nav class="menu">
<span class="bar-1"></span>
<span></span>
<span class="bar-3"></span>
</nav>
</header>
我只希望当bar -1和bar-3从其原始位置移开时过渡平滑。
答案 0 :(得分:2)
您可以像这样简化代码:
#header {
position: fixed;
top: 5vh;
left: 50%;
transform: translateX(-50%);
z-index: 1;
cursor: pointer;
}
nav.menu {
background:
linear-gradient(#3d3d3d,#3d3d3d) top,
linear-gradient(#3d3d3d,#3d3d3d) center,
linear-gradient(#3d3d3d,#3d3d3d) bottom;
background-size:100% 1px;
background-repeat:no-repeat;
width: 30px;
height: 15px;
transition: background-position 1s;
}
nav.menu:hover {
background-position:center;
}
<header id="header">
<nav class="menu">
</nav>
</header>
答案 1 :(得分:0)
不需要javascript。最重要的是,对于top
属性进行动画处理,在这种情况下,您必须设置默认值:
top: 0px;
这里是一个例子:
#header {
position: fixed;
top: 5vh;
left: 50%;
transform: translateX(-50%);
z-index: 1;
cursor: pointer;
}
nav.menu span {
background: #3d3d3d;
width: 30px;
height: 1px;
display: block;
margin-bottom: 6px;
position: relative;
transition: all 1s;
top: 0px;
}
#header:hover .bar-1 {
top: 6px
}
#header:hover .bar-3 {
top: -6px
}
<header id="header">
<nav class="menu">
<span class="bar-1"></span>
<span></span>
<span class="bar-3"></span>
</nav>
</header>