简体   繁体   English

下拉菜单-如何在第二次单击按钮时反转动画?

[英]Drop down menu- how to reverse animation on second click of a button?

I am trying to make a drop down menu using jQuery. 我正在尝试使用jQuery创建下拉菜单。

This is my HTML: 这是我的HTML:

<div class="overlaydiv">This is my menu!</div>  

    <div class="row one">
      <div class="large-12 columns">



      </div>
    </div>


    <div class="row two">
      <div class="large-12 columns">

         <button id="b1">Drop down the menu!</button>   

      </div>
    </div>

CSS for overlay: CSS的叠加层:

.overlaydiv { height: 100vh; width: 100vw; background-color: aquamarine; position: absolute; top: -100%; z-index: 1; }

This is jQuery that drops down the menu on click: 这是jQuery,可在单击时下拉菜单:

$("#b1").on("click", function() {

         $(".overlaydiv").animate({top: "0%"}, 200, 'swing');

      });

What would be the easiest way to reverse animation on second click? 在第二次点击时反转动画的最简单方法是什么?

The best way I can think of is using CSS transition. 我能想到的最好方法是使用CSS过渡。

So, here's the CSS: 因此,这是CSS:

.overlaydiv{ 
    height: 100vh; 
    width: 100vw; 
    background-color: aquamarine; 
    position: absolute; 
    top: -100%; 
    z-index: 1; 
    transition: all 0.2s;
}

.overlaydiv.active{
    top: 0%;
}

And the JS 和JS

$("#b1, .overlaydiv").on("click", function() {

     $(".overlaydiv").toggleClass("active");

});

You can check that to assign class active on your button and make action on it. 您可以检查以在按钮上激活活动 class并对其进行操作。

 $("#b1").on("click", function() { if($(this).hasClass("active")){ $(this).removeClass("active"); $(".overlaydiv").animate({top: "-100%"}, 200, 'swing'); }else{ $(this).addClass("active"); $(".overlaydiv").animate({top: "0%"}, 200, 'swing'); } }); 
 .overlaydiv { height: 100vh; width: 100vw; background-color: aquamarine; position: absolute; top: -100%; z-index: 1; } #b1 {position:relative;z-index:2} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="overlaydiv">This is my menu!</div> <div class="row one"> <div class="large-12 columns"> </div> </div> <div class="row two"> <div class="large-12 columns"> <button id="b1">Drop down the menu!</button> </div> </div> 

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

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