[英]How can I randomize elements selected in a JQuery each loop
I have been working on this functionality where I have 5 circles then when a button is clicked they all move down the page one at a time in order. 我一直在使用此功能,其中有5个圆圈,然后单击一个按钮时,它们都一次按顺序向下移动一页。 I am trying to get them to go down in a random order. 我正试图让他们以随机顺序下降。 (if not random at least something that doesn't make them fall in order) (如果不是随机的,至少不会使它们按顺序下降)
JsFiddle: https://jsfiddle.net/n12zj90p/2/ JsFiddle: https ://jsfiddle.net/n12zj90p/2/
HTML: HTML:
<div class="container">
<button>CLICK</button>
<div class="circle circle-1"></div>
<div class="circle circle-2"></div>
<div class="circle circle-3"></div>
<div class="circle circle-4"></div>
<div class="circle circle-5"></div>
</div>
CSS: CSS:
.circle{
width: 40px;
height: 40px;
position: absolute;
background: red;
border-radius: 100%;
}
.circle-1{ top: 10em; left: 10em; }
.circle-2{ top: 20em; left: 20em; }
.circle-3{ top: 30em; left: 30em; }
.circle-4{ top: 40em; left: 40em; }
.circle-5{ top: 50em; left: 50em; }
button{ padding: 10px 50px; display: table; margin: auto; }
JQUERY: JQUERY:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
$(elem).delay(i * 500).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});
var $c = $(".circle");
is an array. 是一个数组。 So you just need to randomly shuffle it before doing each
on it 因此,您只需要在对其进行each
处理之前随机洗牌
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle($c).each(...
Not sure I deserve any credit for this because it was Pointy's idea, but here's a code that's working and pretty simple: 不确定我是否应该为此功劳,因为这是Pointy的想法,但是下面的代码可以正常工作并且非常简单:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
var rando_time = Math.floor((Math.random() * 600) + 1);
$(elem).delay(i * rando_time).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.