【问题标题】:How can I randomize elements selected in a JQuery each loop如何在每个循环中随机化 JQuery 中选择的元素
【发布时间】:2015-11-06 20:30:05
【问题描述】:

我一直在研究这个功能,我有 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          

    });
});

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

不确定我是否应该为此获得任何荣誉,因为这是 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 

    });
});

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • 如果你将它定义为 $.fn.shuffle 并使用它而不是 o... 你可以在 jquery 方式中使用它:$c.shuffle().each()
    • SMH 这与重复问题中的答案几乎相同。
    • @Popnoodles 是的,数组的改组是相同的,但它的使用方式不同。有些人只有在以不同的方法使用时才能理解解决方案。但是,是的,您认为它的技术方面是相同的,但它的使用方式却不同。
    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多