Close JS Menu on ESC

2019-09-20 04:48发布

I am working on a simple slide-in menu system. I'd like to be able to close a menu by hitting the ESC key.

Here's my current code: http://jsfiddle.net/3w539Lct/3/

Line 126 of my Javascript, you can see:

$( document ).on( 'keydown', function ( e ) {
            if ( e.keyCode === 27 ) { // ESC
                $(".menu-wrap").prop("checked", false);
            }
        });

However, this doesn't work. Can someone help?

3条回答
祖国的老花朵
2楼-- · 2019-09-20 05:09

I reused some of your existing functions and variables. This should be correct.

The element $(."menu-wrap") is a div, and doesn't have a checked property. You need to add the logic of hiding the menu on escape button press.

     $( document ).on( 'keydown', function ( e ) {
        if ( e.keyCode === 27 ) { // ESC
             isOpen && classie.remove( bodyEl, 'show-menu' );
        }
    });

Here's a working demo

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-20 05:14

Trigger the toggleMenu on the condition it's isOpen. like so:

$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) { // ESC
        isOpen && toggleMenu();
    }
});

http://jsfiddle.net/3w539Lct/7/

查看更多
姐就是有狂的资本
4楼-- · 2019-09-20 05:28
$(document).keyup(function(e) {
 if (e.keyCode == 27) {
     toggleMenu();
 }// escape key maps to keycode `27`
});

hope this helps

查看更多
登录 后发表回答