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

标签 javascript jquery html css

我有一个行内 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/

相关文章:

javascript - 刷新页面时删除当前类

jquery - 如何使用 jQuery 选择上下文节点的特定同级节点?

javascript - 当窗口大小调整时,优雅地自动调整 Galleria jQuery 幻灯片的大小

javascript - 如何更改 img 网址? (与/类)

html - 如何让多个图像自动调整大小并在 div 中保持居中

php - 面临一些CSS问题

javascript - 地平线客户端库 : is group-by doable?

javascript - Chrome 扩展 : use chrome. webRequest 用于修改相当于 cURL 请求的 `--data` arg 的 HTTP 请求

javascript - 使用 Promise 运行 Cheerios 的异步调用

html - 使用 -moz-transform 进行 CSS 转换