HTML JQUERY implement ARROW DOWN ON UL/LI

后端 未结 1 1382
暖寄归人
暖寄归人 2021-01-07 12:29

This is a simple requirement and I cannot make it work.

I simply want to navigate through a using arrow keys.Also I want to detect when a arrow key is pressed on a

相关标签:
1条回答
  • 2021-01-07 13:09

    How about something like this jsFiddle?

    Basically it maintains a simple index of which list item is currently selected. The up and down arrow keys are bound to the keydown event and if someone presses the up arrow at the top of the list, the top item stays selected and vice-versa.

    var chosen = "";
    $(document).keydown(function(e){ // 38-up, 40-down
        if (e.keyCode == 40) { 
            if(chosen === "") {
                chosen = 0;
            } else if((chosen+1) < $('li').length) {
                chosen++; 
            }
            $('li').removeClass('selected');
            $('li:eq('+chosen+')').addClass('selected');
            return false;
        }
        if (e.keyCode == 38) { 
            if(chosen === "") {
                chosen = 0;
            } else if(chosen > 0) {
                chosen--;            
            }
            $('li').removeClass('selected');
            $('li:eq('+chosen+')').addClass('selected');
            return false;
        }
    });
    
    0 讨论(0)
提交回复
热议问题