Enabling keyboard navigation in the Bootstrap dropdown-menu

前端 未结 2 1417
栀梦
栀梦 2020-12-30 05:41

Is it possible to navigate using the keyboard to the drop down menu using Tab, and navigate using the arrow keys to the sub elements of the drop down?

Her

相关标签:
2条回答
  • 2020-12-30 06:18

    Nice example.

    But, Why did you set a setTimeout? Some specific reason?

    setTimeout(function(){
        $(".search-option:first").focus();
    },100);
    

    I made the same example, simulating an input select box, without a timeout. Check this out.

    0 讨论(0)
  • 2020-12-30 06:30

    Update

    Bootstrap now supports up/down keys as standard.

    So if you want Tab to activate the dropdown, just get the key code (9) and do the following:

    $('.input-group input').keydown(function(e){
        if(e.which == 9){ // tab
            e.preventDefault();
            $(this).parent().find('.dropdown-toggle').click();
            $(this).parent().find('.dropdown-menu a:first').focus();
        }
    });
    

    And if you want to add further functionality for when the user is focused on a dropdown menu item:

    $('.dropdown-menu a').keydown(function(e){
        switch(e.which){
            case 36: // home
                e.preventDefault();
                $(this).closest('.dropdown-menu').find('a:first').focus();
                break;
            case 35: // end
                e.preventDefault();
                $(this).closest('.dropdown-menu').find('a:last').focus();
                break;
        }
    });
    

    See this JSFiddle for a demo.

    0 讨论(0)
提交回复
热议问题