2016-12-15 111 views
1

我试图用delay逐个更改特定class的背景颜色,而不是同时更改所有内容。更改一个类的背景颜色,有一个延迟一个接一个

.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,然后将其移除并应用到第二个项目div,然后继续? –

+0

[This might help](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')? 好的 – 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

Thankyou,即时通讯要去尝试在我的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" />

相关问题