📌  相关文章
📜  使用 javascript 代码示例使用箭头键(向上和向下)选择 li 元素

📅  最后修改于: 2022-03-11 15:03:03.200000             🧑  作者: Mango

代码示例1
var li = $('#list > li');
var liSelected;
$(window).on('keydown', function(e){
var selected;
if(e.which === 40){
    if(liSelected){
        liSelected.removeClass('background');
        next = liSelected.next();
        if(next.length > 0){
            liSelected = next.addClass('background');
            selected = next.text();

        }else{
            liSelected = li.eq(0).addClass('background');
            selected = li.eq(0).text();
        }
    }else{
        liSelected = li.eq(0).addClass('background');
            selected = li.eq(0).text();
    }
}else if(e.which === 38){
    if(liSelected){
        liSelected.removeClass('background');
        next = liSelected.prev();
        if(next.length > 0){
            liSelected = next.addClass('background');
            selected = next.text();

        }else{

            liSelected = li.last().addClass('background');
            selected = li.last().text()
        }
    }else{

        liSelected = li.last().addClass('background');
        selected = li.last().text()
    }
}
console.log(selected)
});

/*HTML FILE CODE




    
    
    
    
    
    


    
    
  • 1
  • 2
  • 3
*/