2016-11-17 60 views
0

我有一個問題,因爲我想用這個很酷的動畫漢堡菜單按鈕(「navicon1」)編碼一個邊欄。菜單按鈕的一個很酷的動畫效果用於「打開」類。如果我點擊菜單按鈕,我想切換功能「openNav」和「closeNav」。Javascript:使用1 Click-Listener切換2個函數

原來這就是我想要的:

  • 如果我點擊菜單鍵(navicon1)第一次 - >菜單按鈕 改變爲X(這工作)和執行javascript函數「openNav」
  • 如果我點擊菜單鍵(navicon1)第二次 - >菜單按鈕 改變正常(這個工程)和執行javascript函數 「closeNav」

這裏是我的代碼:

$(document).ready(function() { 

     $('#navicon1,#navicon2,#navicon3,#navicon4').click(function() { 
      $(this).toggleClass('open'); 

     }); 
    }); 
    /* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */ 
    function openNav() { 

     document.getElementById("mySidenav").style.width = "75%"; 
     document.getElementById("main").style.marginLeft = "75%"; 
     document.body.style.backgroundColor = "rgba(0,0,0,0.4)"; 

     } 

     /* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */ 
    function closeNav() { 

     document.getElementById("mySidenav").style.width = "0"; 
     document.getElementById("main").style.marginLeft = "0"; 
     document.body.style.backgroundColor = "white"; 
     check = 0; 
     } 

可以忽略navicon2-3,他們只對三網融合

謝謝您的幫助:)

回答

1

使用一個變量來記住的狀態:

var navOpen = false; 
$("#navicon1").click(function() { 
    if (navOpen) { 
     closeNav(); 
     navOpen = false; 
    } else { 
     openNav(); 
     navOpen = true; 
    } 
}); 
+0

工作完全謝謝! :) –

+0

@DreLoo記得標記答案爲回答,如果它回答你的問題。 – IMTheNachoMan

1

我建議創建一個函數來處理toggleClass()並根據狀態從那裏調用其他函數。

$('#navicon1').click(function() { 
    $(this).toggleClass('open'); 

    //if hasClass() then call function to open it 

    //else call function to close it 

}); 
+0

他只想在點擊「navicon1」時切換導航欄,而不是所有其他導航欄。 – Barmar

+0

我錯過了,謝謝。編輯。 – Falk