单击屏幕或其他按钮时关闭菜单

时间:2018-09-20 17:48:01

标签: javascript jquery menu

我有两个垂直菜单和两个按钮。如果单击每个菜单,则仅打开和关闭每个菜单。

但是我希望通过单击“ showLeft”按钮来隐藏“ showRight”菜单。

如果我在监视器上的任意位置单击,两个菜单将关闭

<button id="showLeft">Show/Hide Left Slide Menu</button>
<button id="showRight">Show/Hide Right Slide Menu</button>

<script>
    var menuLeft = document.getElementById( 'cbp-spmenu-s1' ),
        menuRight = document.getElementById( 'cbp-spmenu-s2' ),
        body = document.body;

    showLeft.onclick = function() {
        classie.toggle( this, 'active' );
        classie.toggle( menuLeft, 'cbp-spmenu-open' );
        disableOther( 'showLeft' );

    };
    showRight.onclick = function() {
        classie.toggle( this, 'active' );
        classie.toggle( menuRight, 'cbp-spmenu-open' );
        disableOther( 'showRight' );
    };


    function disableOther( button ) {
        if( button !== 'showLeft' ) {
            classie.toggle( showLeft, 'disabled' );
        }
        if( button !== 'showRight' ) {
            classie.toggle( showRight, 'disabled' );
        }
    }           

    var topNavBar = 50;
    var footer = 48;
    var height = $(window).height();
    $('.cbp-spmenu').css('height', (height - (topNavBar+footer)));

    $(window).resize(function(){
        var height = $(window).height();
        $('.cbp-spmenu').css('height', (height - (topNavBar+footer)));
    });


</script>

2 个答案:

答案 0 :(得分:1)

Working fiddle

单击时,需要删除另一个菜单的类cbp-spmenu-open

showLeft.onclick = function() {
  classie.toggle(this, 'active');
  classie.toggle(menuLeft, 'cbp-spmenu-open');
  classie.remove(menuRight, 'cbp-spmenu-open');
};

showRight.onclick = function() {
  classie.toggle(this, 'active');
  classie.toggle(menuRight, 'cbp-spmenu-open');
  classie.remove(menuLeft, 'cbp-spmenu-open');
};

答案 1 :(得分:0)

由于没有名为showLeftshowRight的对象,您的意思是分别是menuLeft.onclickmenuRight.onclick而不是showLeft.onclickshowRight.onclick吗?

如果仍然无法解决,您可以在控制台中共享任何JS错误吗?