2016-12-15 7 views
1

classの背景色をdelayで1つ1つずつ変更しようとしていますが、すべてを同時に変更するつもりはありません。1つのクラスの背景色を1つずつ遅らせて変更する

.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

確認するには、最初の項目divに緑色の背景色を適用し、それを削除して2番目の項目に適用したいのですか? –

+0

[これは役立つかもしれません](http://stackoverflow.com/questions/25351205/changing-color-of-multiple-divs-one-after-another) –

答えて

1

はタイムアウトのインクリメント値で設定したタイムアウトを使用して、シンプルなソリューションです

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

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

ありがとう!これは固定=) –

+0

@ Lauriantiそれはいいようですが、このコードは最小です。あなたの答えに感謝します。 –

+0

これは最低ですか? $( '。item')。asyncCss( 'backgroundColor'、 'red')? ok – Laurianti

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>

+0

ありがとう、私のjavascriptでこれを処理しようとするつもりです。 cssを動的に追加します。 –

0

jQuery.fn.extend({ 
 
\t asyncCss: function(a, b, c) { 
 
    \t 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" />