简体   繁体   English

CSS Transition不适用于“汉堡包”按钮

[英]CSS Transition doesn't work with hamburger button

I made a hamburger button and I'm trying to animate spans to create a cross. 我制作了一个汉堡包按钮,并尝试对跨度进行动画处理以创建一个十字架。

My transition doesn't work and I don't know why... I found that sometimes transitions doesn't work on chrome so I've used webkit prefix but it didn't help :( 我的过渡无法正常工作,我也不知道为什么...我发现有时过渡不适用于chrome,因此我使用了webkit前缀,但无济于事:(

This is my HTML code: 这是我的HTML代码:

<div class="main__box__nav__hamburger">
    <span class="line line1"></span>
    <span class="line line2"></span>
    <span class="line line3"></span>
</div>

CSS code: CSS代码:

.main__box__nav__hamburger {
  min-width: 30px;
  height: 20px;
  margin: 45px 10px;
  position: relative;
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}
.line {
  position: absolute;
  min-width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #000;
}
.line2 {
  top: 8px;
}
.line3 {
  top: 16px;
}
.main__box__nav__hamburger.close .line1 {
  transform: rotate(45deg);
  top: 50%;
}
.main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 {
  transform: rotate(-45deg);
  top: 50%;
}

That is because you are applying the transition to the parent element (the hamburger itself), instead of to its children. 这是因为您将过渡应用于父元素(汉堡本身),而不是其子元素。 Remember that transition is not inherited. 请记住, transition不是继承的。

Move the transition property to the .line selector and it will work: transition属性移至.line选择器,它将起作用:

.line {
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}

See proof-of-concept below (I have added some minimal JS, so clicking on the hamburger will toggle the close class needed to visualize the transition): 请参阅下面的概念验证(我添加了一些最小的JS,因此单击汉堡包将切换可视化过渡所需的close类):

 var burger = document.querySelector('.main__box__nav__hamburger'); burger.addEventListener('click', function() { this.classList.toggle('close'); }); 
 .main__box__nav__hamburger { min-width: 30px; height: 20px; margin: 45px 10px; position: relative; } .line { position: absolute; min-width: 30px; height: 4px; border-radius: 2px; background: #000; transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s; } .line2 { top: 8px; } .line3 { top: 16px; } .main__box__nav__hamburger.close .line1 { transform: rotate(45deg); top: 50%; } .main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 { transform: rotate(-45deg); top: 50%; } 
 <div class="main__box__nav__hamburger"> <span class="line line1"></span> <span class="line line2"></span> <span class="line line3"></span> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM