javascript - 循环遍历 div

标签 javascript jquery

看一下这段代码: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/

相关文章:

javascript - 使用 JQuery 在 HTML 中查找具有特定名称属性或 ID 的元素

javascript - UI 动画 Jquery 与 AngularJS

jquery - 为 sencha-touch 中的 jquery 转换预加载 css-background-images

javascript - 为什么 Kendo UI destroy 方法会删除所有子部件?

javascript - 当用户单击表格第二列的标题时更改第二列的值

javascript - 检查是否在 Angular 中注入(inject)了依赖项

javascript - 使用canvas globalAlpha进行淡入淡出

javascript - Highcharts 词云 - 为每个词建立链接

javascript - 为什么javascript会添加一个随机样式标签?

jquery - 使用 event.target 获取类值?