2016-11-17 22 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