2017-02-08 6 views
1

jQueryを使用してドロップダウンメニューを作成しようとしています。ドロップダウンメニュー - ボタンの2回目のクリックでアニメーションを反転する方法は?

これは私の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:

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

これはクリックのメニューをドロップダウンするというjQueryのです:

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

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

     }); 

一番簡単だろう何2回目のクリックでアニメーションを反転させる方法は?

答えて

2

私が考えることができる最良の方法は、CSSトランジションを使用することです。あなたはそれがあなたのボタンのclassアクティブを割り当て、それに行動をするためにチェックすることができ

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

.overlaydiv.active{ 
    top: 0%; 
} 

そしてJS

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

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

}); 
+0

あなたはそのコードを試してみましたしましたか?私はそれを働かせることはできません。 – user7393973

+0

@ user7393973私は(私のものをすでに詰め込んでいませんでしたが)質問から私はOPの元のコードが動作していると仮定しますので、私はちょうどそこから外挿します –

+0

@ user7393973私は編集しました。今働いているはずです。ここでは、フィドルですhttps://jsfiddle.net/fw3d3fah/ –

0

だから、ここCSSです。

$("#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>

関連する問題