【发布时间】:2018-04-02 09:39:43
【问题描述】:
我试图让几个球在给定的 div 中进行随机位移。用于创建球和设置球样式的代码几乎完全在 jQuery 中,并且它可以工作,问题是试图让 .animate() 一直循环,让球在每次迭代中以随机方向/速度移动。
第一步有效,但其余部分无效。这是链接:https://jsfiddle.net/xpvt214o/19871/
// Some random colors
var colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
var numBalls = 50;
var balls = [];
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $('.front-bg').height();
var w = $('.front-bg').width();
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
for (i = 0; i < numBalls; i++) {
$('.front-bg').append('<div class="ball"></div>');
$('.ball').each(function(index, el) {
$(this).css('backgroundColor', colors[Math.floor(Math.random() * colors.length)]);
$(this).css('left', Math.floor(Math.random() * 100) + '%');
$(this).css('top', Math.floor(Math.random() * 100) + '%');
$(this).css('transform', 'scale(' + Math.random() + ')');
var WH = Math.floor(Math.random() * 45) + 4;
$(this).css({
width: WH + 'px',
height: WH + 'px'
});
});
}
$('.ball').each(function() {
var newq = makeNewPosition();
$(this).animate({
top: newq[0],
left: newq[1],
easing: 'easeInOutQuint',
complete: function() {
$(this).animate({
top: newq[0],
left: newq[1],
easing: 'easeInOutQuint',
}, Math.random() * 10000)
}
}, Math.random() * 10000);
});
【问题讨论】:
标签: jquery jquery-animate