我想要一个动画,在其中我为div分配随机的left和top值并对其进行动画处理,但还希望动画在完成后重新启动。所以我在自己内部触发了animate函数,但是在第一个动画之后,只有最后一个重复的div元素正在动画。我确实是这样的:
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
$(".dot").each(function(){
var abc = getRandomArbitrary(0,100);
var xyz = getRandomArbitrary(0,100);
var aaa = getRandomArbitrary(0,100);
var yyy = getRandomArbitrary(0,100);
$(this).css({"left": abc+"%", "top": xyz+"%"})
$thiss = $(this);
for(var i=0; i< $(".dot").length;i++){
function anim(){
$thiss.animate({"left":yyy+"%", "top": aaa+"%"},1000,function(){
anim();
});
console.log(i)
}
}
anim();
});
的HTML:
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
CSS:
.dot{width: 8px; height: 8px; border-radius: 100%; background: red; position: absolute;}
jsfiddle:https://jsfiddle.net/qfcmfzw7/
摆弄我没有使用“ for”的地方:https://jsfiddle.net/744sx34v/
最佳答案
将功能移至单独的功能并在循环中调用它:
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function anim(object){
var aaa = getRandomArbitrary(0,100);
var yyy = getRandomArbitrary(0,100);
object.animate({"left":yyy+"%", "top": aaa+"%"},1000,function(){
anim(object);
});
}
$(".dot").each(function(){
// set the initial position of each div
var abc = getRandomArbitrary(0,100);
var xyz = getRandomArbitrary(0,100);
$(this).css({"left": abc+"%", "top": xyz+"%"});
// call the animate function which calls itself recursively
anim($(this));
});
.dot{width: 8px; height: 8px; border-radius: 100%; background: red; position: absolute;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>