在每个循环中工作的最后一个元素
问题描述:
我想要一个动画,其中我将随机左值和顶值赋值给div并为其设置动画,但也希望动画在完成后重新启动。所以我发射了自己的动画函数,但在第一个动画之后,只有最后一个重复的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/ 小提琴这里我因此未使用 '为':https://jsfiddle.net/744sx34v/
答
移动功能,以一个单独的功能和循环中调用它:
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function anim(object){
\t 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);
\t $(this).css({"left": abc+"%", "top": xyz+"%"});
// call the animate function which calls itself recursively
\t 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>
+0
非常感谢@KAD! – user3450590
+0
欢迎您:) – KAD
答
你不需要for
循环,需要递归调用animate()
特定元素也随机设置top
和left
CSS属性。
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
$(".dot").each(function() {
//Initially set left and top afterwards animate will take care of it
var left = getRandomArbitrary(0, 100);
var top = getRandomArbitrary(0, 100);
$this = $(this);
$this.css({
"left": left + "%",
"top": top + "%"
})
animate($this);
});
function animate($this) {
var left = getRandomArbitrary(0, 100);
var top = getRandomArbitrary(0, 100);
$this.animate({
"left": left + "%",
"top": top + "%"
}, 1000, function() {
animate($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>
用于演示使用''片断 – guradio
你请可以做一个清晰的小提琴链接提供 –