gpt4 book ai didi

javascript - 使用箭头键选择并突出显示元素

转载 作者:行者123 更新时间:2023-11-28 06:17:17 28 4
gpt4 key购买 nike

我有一个行内 block 框列表。第一个框被设置为事件状态并突出显示。通过使用箭头键,我想将其旁边的框设置为事件状态。哪个 JS 事件在这里最好?

js fiddle

HTML

<ol>
<li class="active"></li>
<li></li>
<li></li>
</ol>

JS

$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
$('li').addClass('active');
break;

case 38: // up
$('li').addClass('active');
break;

case 39: // right
$('li').addClass('active');
break;

case 40: // down
$('li').addClass('active');
break;

default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});

CSS

li {
display: inline-block;
padding: 50px;
border: solid;
counter-increment: step-counter;
margin: 20px;
}

最佳答案

请检查这个fiddle

The up and down can't be accurate because this depends on the style of the sheet

可以使用index来指定元素的索引

        index--;
if (index==-1){index=$("#orderedList li").length-1;}
$('li').removeClass('active');
$($('li')[index]).addClass('active');

关于javascript - 使用箭头键选择并突出显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824424/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com