Javascript:使用 1 个 Click-Listener 在 2 个函数之间切换

Javascript: Switch between 2 functions with 1 Click-Listener

我想用这个很酷的动画 Burger-Menu-Button("navicon1") 编写侧边栏代码。 "open" class 使用了菜单按钮的炫酷动画效果。如果单击菜单按钮,我也想切换功能 "openNav" 和 "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,它们仅适用于 css...

感谢您的帮助:)

使用变量来记住状态:

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

我建议创建一个函数来处理 toggleClass() 并根据状态从那里调用其他函数。

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

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

    //else call function to close it

});