Jquery 循环通过具有数字顺序id名称的div?

Jquery 循环通过具有数字顺序id名称的div?,jquery,html,css,Jquery,Html,Css,我有4个div,id名为type1、type2、type3和type4。我需要一些jquery的帮助,它为第一个div提供一个绿色背景,然后在2秒钟后,下一个div获得一个绿色背景,第一个div返回到正常的背景色,依此类推。我需要循环永远持续下去 <div id="type1"> <p>Hey</p> </div> <div id="type2"> <p>Hello></p> </div>

我有4个div,id名为type1、type2、type3和type4。我需要一些jquery的帮助,它为第一个div提供一个绿色背景,然后在2秒钟后,下一个div获得一个绿色背景,第一个div返回到正常的背景色,依此类推。我需要循环永远持续下去

<div id="type1">
<p>Hey</p>
</div>

<div id="type2">
<p>Hello></p>
</div>

<div id="type3">
<p>Hey again</p>
</div>

<div id="type4">
<p>Hello again</p>
</div>

你好>

又来了

你好


如果你在div上加了一个类名,比如说“type”,并且div少于10个,这就行了。这也适用于其他情况,但您需要对排序例程做一些修改

orderDivs = $(".type").sort(asc_sort);
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
    return ($(b).attr('id')) < ($(a).attr('id')) ? 1 : -1;    
}
var divSize = orderDivs.length;
var currentDiv = divSize -1;
var lastDiv = orderDivs[divSize-1];
console.log(orderDivs[0]);
function highLightNext() {
    $(lastDiv).css('background-color','transparent');
    currentDiv = (currentDiv+1) % divSize;
    lastDiv = orderDivs[currentDiv]; 
    $(lastDiv).css('background-color','green');
    setTimeout(highLightNext,1000);
}

highLightNext();
orderDivs=$(“.type”).sort(asc\u-sort);
//$(“#调试”).text(“输出:”;
//收尾排序
函数asc_排序(a,b){
返回($(b).attr('id'))<($(a).attr('id'))?1:-1;
}
var divSize=orderDivs.length;
var currentDiv=divSize-1;
var lastDiv=orderDivs[divSize-1];
console.log(orderDivs[0]);
函数highLightNext(){
css('background-color','transparent');
currentDiv=(currentDiv+1)%divSize;
lastDiv=orderDivs[currentDiv];
$(lastDiv).css('background-color','green');
设置超时(highLightNext,1000);
}
highLightNext();

您可以使用JQuery实现这一点,有很多方法可以实现这一点

小提琴:

编辑: 这不会无限循环(没有正确阅读描述) 正在修复该问题:)

HTML:

<div class="type">
<p>Hey</p>
</div>

<div class="type">
<p>Hello></p>
</div>

<div class="type">
<p>Hey again</p>
</div>

<div class="type">
<p>Hello again</p>
</div>
JQuery:

$(".type").each(function (i) {
    $(this).delay(2000*i).queue(function() { 
       $(this).addClass('green');
         $(this).prev().removeClass('green');
    })
});

为了完整起见,我想指出,这可以在没有Javascript的情况下完成

使用
css动画

加成
代码的哪一部分工作不正常<代码>ids具有相同前缀的可能应该是类。您可以通过显示顺序来执行此操作,还是id顺序不同?会有超过10个ID吗?好吧,假设我使用了类,并将所有div命名为类“type”。我如何使用jquery循环它们呢?我建议添加类,然后您可以使用该类获得元素数组。我想其他人要求的是,你至少在做你要求的事情时先表现出一些努力。@BrianHoover不,不幸的是,我不能按显示顺序来做。不会有超过10个ID。
$(".type").each(function (i) {
    $(this).delay(2000*i).queue(function() { 
       $(this).addClass('green');
         $(this).prev().removeClass('green');
    })
});
<div class="animated"></div>
<div>
<p>Hey</p>
</div>

<div>
<p>Hello></p>
</div>

<div>
<p>Hey again</p>
</div>

<div>
<p>Hello again</p>
</div>
.animated
{
    position:absolute;
    top:0;
    background:green;
    z-index:-1;
    animation: move 8s steps(4) infinite;    
}

@keyframes move {
  from { top: 0; }
  to   { top: 400px; }
}