ul list not scrolling on key press but it does with mouse wheel

后端 未结 1 957
执念已碎
执念已碎 2021-01-13 05:50

I\'m working with Bootstrap 3 and i have an autossugest input. The problem is that i want the

    to scroll with the keyboard keys but it doesn\'t work.
相关标签:
1条回答
  • 2021-01-13 06:43

    Final Edit:

    Alright, I started having too much fun figuring this out, and finally have (hopefully you still need the solution!) Here is a working solution, building off of what I posted earlier. I hope it's what you were looking for!

    $('#test').keydown(function(e) {
        if($('.dropdown-menu').is(':visible')) {
    
            var menu = $('.dropdown-menu');
            var active = menu.find('.active');
            var height = active.outerHeight(); //Height of <li>
            var top = menu.scrollTop(); //Current top of scroll window
            var menuHeight = menu[0].scrollHeight; //Full height of <ul>
    
            //Up
            if(e.keyCode == 38) {
                if(top != 0) {
                    //All but top item goes up
                    menu.scrollTop(top - height);
                } else {
                    //Top item - go to bottom of menu
                    menu.scrollTop(menuHeight + height);
                }
            }    
            //Down
            if(e.keyCode == 40) {
                //window.alert(menuHeight - height);
                var nextHeight = top + height; //Next scrollTop height
                var maxHeight = menuHeight - height; //Max scrollTop height
    
                if(nextHeight <= maxHeight) {
                    //All but bottom item goes down
                    menu.scrollTop(top + height);
                } else {
                    //Bottom item - go to top of menu
                    menu.scrollTop(0);
                }
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题