看一下这段代码:jsfiddle
使用箭头键在 div 列表中循环。正如您所看到的,“Mark”之后和“Luca”上方有一个间隙。换句话说;在某些时候,没有一个 div 具有蓝色背景。我的问题:如何在没有间隙的情况下循环使用 div?
(首先聚焦输入)
最佳答案
我可能会使用 modulo operator 寻求解决方案(%
) 当选择索引小于或大于元素数量时将其重置为 0:
var curr = $('#display').find('.current');
ind = curr.index(),
all = curr.parent().children(),
adj = e.keyCode == 40 ? 1 : -1;
if (!curr.length)
all = $("#display").children(), ind = e.keyCode == 40 ? -1 : 0;
$(curr).attr('class', 'display_box');
all.eq((ind + adj) % all.length).attr('class', 'display_box current');
示例:http://jsfiddle.net/sjKgF/50/
(编辑:修复了由于鼠标悬停重置而最初没有突出显示任何项目的边缘情况)。
(编辑 2:重构。您可以看到,使用模数可以让我们摆脱一些 if 语句并缩短代码)。
关于javascript - 循环遍历 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077944/