改变一个类的背景颜色,一个接一个地延迟

时间:2016-12-15 09:59:04

标签: javascript jquery html css

我正在尝试使用class逐个更改特定delay的背景颜色,而不是同时更改所有内容。

.item {
  height: 50px;
  width: 50px;
  background-color: green;
  margin-top: 10px;
}
<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

3 个答案:

答案 0 :(得分:4)

评论显示JS的解决方案。所以我将通过添加一种方法在CSS中完成此操作,只有动画和延迟:

.item {
  height: 50px;
  width: 50px;
  margin-top: 10px;
  background: black;
  animation: colorit 0.5s linear;
  -webkit-animation-fill-mode: forwards;
  -moz-animation-fill-mode: forwards;
  -o-animation-fill-mode: forwards;
  -ms-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}
.item:nth-child(2) {
  animation-delay: 0.5s;
}
.item:nth-child(3) {
  animation-delay: 1s;
}
.item:nth-child(4) {
  animation-delay: 1.5s;
}
@keyframes colorit {
  from {
    background-color: black;
  }
  to {
    background-color: green;
  }
}
@-webkit-keyframes colorit {
  from {
    background-color: black;
  }
  to {
    background-color: green;
  }
}
<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

答案 1 :(得分:1)

这是一个简单的解决方案,使用set timeout和超时的递增值

http://codepen.io/Vall3y/pen/woQPeE

$('.item').each(function(i, item) {
  setTimeout(function() {
    item.classList.add('item--colored')
  }, i * 250);
});

答案 2 :(得分:0)

jQuery.fn.extend({
	asyncCss: function(a, b, c) {
    	var args = arguments;
          return this.each(function(i) {
            var j = $(this);
            setTimeout(function() {
                j.css.apply(j, args);
            }, i * 1000);

          });
        }
    });

function changeCssAsync() {
  $('.item').asyncCss({
      backgroundColor: 'red',
      width: '10px',
      height: '10px'
  });
}
.item {
  height: 50px;
  width: 50px;
  background-color: green;
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item"></div>

<div class="item"></div>

<div class="item"></div>

<div class="item"></div>

<input type="button" onclick="changeCssAsync()" value="Use me as .css() function" />