【问题标题】:Javascript: Switch between 2 functions with 1 Click-ListenerJavascript:使用 1 个 Click-Listener 在 2 个函数之间切换
【发布时间】:2017-04-01 15:24:13
【问题描述】:

我有一个问题,我想用这个很酷的动画汉堡菜单按钮(“navicon1”)编写一个侧边栏。 Menu-Button 的一个很酷的动画效果是使用“open”类。如果单击菜单按钮,我也想切换功能“openNav”和“closeNav”。

这就是我想要的:

  • 如果我第一次单击菜单按钮 (navicon1) -> 菜单按钮 更改为 X(可行)并执行 javascript 函数“openNav”
  • 如果我第二次单击菜单按钮 (navicon1) -> 菜单按钮 更改为正常(这有效)并执行 javascript 函数 “关闭导航”

这是我的代码:

  $(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...

感谢您的帮助:)

【问题讨论】:

    标签: javascript function menu toggle sidebar


    【解决方案1】:

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

    $('#navicon1').click(function() {
        $(this).toggleClass('open');
    
        //if hasClass() then call function to open it
    
        //else call function to close it
    
    });
    

    【讨论】:

    • 他只想在你点击navicon1时切换导航栏,而不是所有其他导航图标。
    【解决方案2】:

    使用变量来记住状态:

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

    【讨论】:

    • 完美工作 谢谢! :)
    • @DreLoo 如果回答了您的问题,请记住将答案标记为已回答。
    猜你喜欢
    • 2016-06-10
    • 2023-01-22
    • 2016-03-04
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多