我想利用css动画能力做出无限动作的优势来控制我每次以不同的值为目标的孩子然后在某些时候回到零等等。 让我们说我想为一组3个DIV的背景着色,所以CSS代码将是:
<style>
div:nth-of-type(1){
-webkit-animation:coloring 2s infinite;
}
@-webkit-keyframes coloring{
from {background:red;}
to {background:yellow;}
}
<style>
所以只要我使用无限属性它就会永远存在,在这里我想连续每次增加nth-of-type的值(1,2,3)然后当它到达3时它将返回到1
答案 0 :(得分:1)
非常有趣的问题。但我不认为CSS支持循环功能。
:nth-of-type()
可以计算不同的索引,但结果将被禁用为一个数组选择:
:nth-of-type(0,1,2,3)
。这不支持任何迭代,所有元素将立即被选中。
然而,这可以在javascript / jQuery中使用,因为它支持迭代:
var count = 0;
var delay = 0;
$('div').each(function()
{
$('div:eq(' + count +')').delay(delay)
.queue(function()
{
$(this).css('background', 'yellow');
})
count++;
delay += 500;
})
它将迭代每个div元素。对于.eq()
选择器,将选择基于索引值的每个元素,这样逐个选择每个元素。
通常这会在几秒钟内完成,所以你不会看到“一个一个”的效果。
我使用delay()
在选择器上有延迟,其中延迟将在每次迭代时增加。在这种情况下,每半秒后会添加一个新的.queue()
,因此每个函数在队列完成之前不会迭代。
将其与css transition结合使用以获得淡入效果:
transition: background 2s;
-webkit-transition: background 2s; /* Safari */
<强> jsFiddle 强>
答案 1 :(得分:1)
试试这个:
HTML:
<div class="div active"></div>
<div class="div"></div>
<div class="div"></div>
CSS:
.active {
-webkit-animation:coloring 3s;
}
JS:
var len = $(".div").length;
setTimeout(function () {
change_bg();
},3000);
function change_bg() {
var index = $(".active").index(); // get index of active div
var current;
$(".active").removeClass("active");
if (index == len - 1) { // check if active div is last
current = 0; // if last then start from first
} else {
current = index + 1; // increment otherwise
}
$(".div:eq(" + current + ")").addClass("active"); //change background of next div
setTimeout(function () { //recursive calling
change_bg();
},3000);
}
答案 2 :(得分:0)
我正在查看我的问题,我想分享一种使用纯CSS实现此目标的不同方法:
@keyframes coloring {
0% {
background:red;
}
25% {
background:yellow;
}
33% {
background:#ccc;
}
75% {
background:#ccc;
}
100%{
background:#ccc;
}
}
.div {
height:50px;
background:#ccc;
}
.first {
-webkit-animation:coloring 9s ease-out 0s infinite;
animation:coloring 9s ease-out 0s infinite;
-moz-animation:coloring 9s ease-out 0s infinite;
-webkit-animation:coloring 9s ease-out 0s infinite;
}
.second {
-webkit-animation:coloring 9s ease-out 3s infinite;
animation:coloring 9s ease-out 3s infinite;
-moz-animation:coloring 9s ease-out 3s infinite;
-webkit-animation:coloring 9s ease-out 3s infinite;
}
.third {
-webkit-animation:coloring 9s ease-out 6s infinite;
animation:coloring 9s ease-out 6s infinite;
-moz-animation:coloring 9s ease-out 6s infinite;
-webkit-animation:coloring 9s ease-out 6s infinite;
}
<div class="div first"></div>
<div class="div second"></div>
<div class="div third"></div>