gpt4 book ai didi

javascript - 我如何随机化在 JQuery 每个循环中选择的元素

转载 作者:行者123 更新时间:2023-11-28 15:59:18 24 4
gpt4 key购买 nike

我一直在研究这个功能,我有 5 个圆圈,然后当单击一个按钮时,它们都会按顺序一次一个地向下移动页面。我试图让它们以随机顺序下降。 (如果不是随机的,至少是一些不会让它们按顺序排列的东西)

JsFiddle: https://jsfiddle.net/n12zj90p/2/

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:

.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:

$(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"); 是一个数组。所以你只需要在对它进行 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(...

Shuffle comes from here

关于javascript - 我如何随机化在 JQuery 每个循环中选择的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com