如何在点击汉堡包按钮时切换+ - 图标

时间:2015-05-15 20:17:36

标签: jquery

我有这段代码来控制菜单/子菜单。如果我单击+图标切换子菜单,将切换 - 图标。 但是,如果我单击顶部功能区/汉堡按钮,以便移动菜单和子菜单关闭,那么如果我单击 汉堡按钮再次 - 图标仍然存在它应该是+图标。我该怎么做才能让它发挥作用?

谢谢。

Menu Demo. Make window size about 800px

// DOM ready
$(function() {

    // Add some classes and Append the mobile icon nav
    $('.nav').append($('<div class="nav-mobile"></div>'));
    $('.nav > ul').addClass('nav-list');
    $('.nav > ul > li').addClass('nav-item');
    $('.nav > ul > li > ul').addClass('nav-submenu');
    $('.nav > ul > li > ul > li').addClass('nav-submenu-item');

    // Add a <span> to every .nav-item that has a <ul> inside. And add an sub menu icon indicator.
    $('.nav-item').has('ul').prepend('<span class="nav-click"><i></i></span>');

    // Click to reveal the mobile menu
    $('.nav-mobile').click(function(){
    $('.nav-list').toggle();
    $('.nav-submenu').hide(); // This will close the submenu when i click the top ribbon (.nav-mobile) to close the mobile menu
    });

    // Dynamic binding to on 'click' and Toggle the nested nav
    $('.nav-list').on('click', '.nav-click', function(){
    $(this).siblings('.nav-submenu').toggle();

    // This will toggle the + and - when clicked
    $(this).removeClass('nav-click');
    $(this).toggleClass('icon-close');
    $(this).toggleClass('nav-click');

});

1 个答案:

答案 0 :(得分:1)

在您的代码中,当您有人点击某个子菜单项时,您很可能需要删除或切换您添加的icon-close课程。由于您只需切换父nav-list,因此内部项也可能无法关闭。

// Click to reveal the mobile menu
$('.nav-mobile').click(function(){
    $('.nav-list').toggle();
    $('.nav-submenu').hide(); // This will close the submenu when i click the top ribbon (.nav-mobile) to close the mobile menu
    if(!$('.nav-list').is(':visible')){ // the menu was closed because it's not visible anymore
        $('.nav-item .nav-click').each(function(){ //loop through nav clicks
            if($(this).hasClass('icon-close')) {
                $(this).toggleClass('icon-close');              
            }
        }); 
    }
});

我没有测试过这段代码,但我认为你会得到这个想法:)