使用setTimeout临时更改div background-color

时间:2016-07-10 16:18:45

标签: javascript jquery css

我尝试创建一个循环遍历四个div中的每一个的效果,并将其颜色更改为绿色,然后再将其更改为原始并继续下一个。现在它只是永久地改变颜色。我不知道如何解决这个问题,以便在转到下一个之前颜色会改变,因为我正在删除'每个先前元素,以便正确循环。我可能做了七件事,并且不胜感激。

这是一个有效的JSBin:https://jsbin.com/puricazuxa/4/edit?html,css,js,output

使用Javascript:

arrayCount=[1,2,3,4];
var secondPrint = function(){
  setTimeout(function(){
if (arrayCount.length>0){
      $("#button"+arrayCount[0]).attr("class", "sButton2");

     arrayCount.shift(1);
     secondPrint();
   }
}    ,1000);
  };

secondPrint();

CSS:

body {
  background-color: rgb(200,200,200);
  font-family: "Arial";

}
.sButton{
  height: 50px;
  width: 50px;
  margin: 5px;
  padding: 10px;
  border: 2px solid black;
  display:inline;
  background-color: rgb(50,100,100);
}
.sButton2{
  height: 50px;
  width: 50px;
  margin: 5px;
  padding: 10px;
  border: 2px solid black;
  display:inline;
  background-color: rgb(100,200,100);
}

HTML:

<head>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>


</head>
<body>
<!-- Main page placeholders -->

<br/>
<br/>
<div class = "sButton" id="button1">1</div>
<div class = "sButton" id="button2">2</div>
<div class = "sButton" id="button3">3</div>
<div class = "sButton" id="button4">4</div>

1 个答案:

答案 0 :(得分:3)

你的逻辑在这里有点瑕疵。更好的方法是使用setInterval()每秒更新按钮的状态,在每次调用函数时移动到下一个按钮。试试这个:

var secondPrint = function() {
    var $buttons = $('.sButton');
    var $active = $buttons.filter('.sButton2');
    $active = (!$active.length || $active.is(':last')) ? $('.sButton:first') : $active.next();
    $buttons.removeClass('sButton2');
    $active.addClass('sButton2');
};

setInterval(secondPrint, 1000)
secondPrint();

Example fiddle

  

如何在一次迭代后停止它们?我没有使用过setInterval(),因为我不想让它永远继续下去

在这种情况下,您只需要修改逻辑检查以清除:last条件命中时的间隔,如下所示:

var interval;
var secondPrint = function() {
    var $buttons = $('.sButton');
    var $active = $buttons.filter('.sButton2');
    $buttons.removeClass('sButton2');
    if ($active.is(':last')) {
        clearInterval(interval);
        return;
    }

    $active = !$active.length ? $('.sButton:first') : $active.next();
    $active.addClass('sButton2');
};

interval = setInterval(secondPrint, 1000)
secondPrint();

Updated fiddle

相关问题