以随机顺序定位和循环对象

positioning and looping an objects in random order

本文关键字:循环 对象 定位 随机 顺序      更新时间:2023-09-26

我已经创建了 3 个球,我想运行一个循环,通过执行以下操作来对它们进行动画处理:

  1. 随机放置它们
  2. 给他们一个起点
  3. 给他们一个持续时间

这是小提琴链接:http://jsfiddle.net/X3SVp/1/

爪哇语

function flipper(){
    $('#ball_1').animate({
        "left": '-90',
    }, function(){
        $('#ball_1').animate({
            "left": '200',
        }, flipper());
    });
}
flipper();

.HTML

<div id="ball_1">
</div>
<div id="ball_2">
</div>
<div id="ball_3">
</div>

.CSS

#ball_1{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
    left: 200px;
    position: absolute;
}
#ball_2{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
}
#ball_3{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
}

像这样的事情呢:

JavaScript

function flipper() {
    $('.ball').each(function () {
        var rndm = Math.floor(Math.random() * 201);
        $(this).animate({
            "left": '-' + rndm
        }, function () {
            $('.ball').animate({
                "left": rndm
            }, flipper());
        });
    });
}
flipper();

.HTML

<div id="ball_1" class="ball"></div>
<div id="ball_2" class="ball"></div>
<div id="ball_3" class="ball"></div>

.CSS

#ball_1 {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
    left: 200px;
    position: relative;
}
#ball_2 {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
    position: relative;
}
#ball_3 {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #354390;
    position: relative;
}

在这里摆弄

作为指导点,无需为您完成所有工作。

创建一个在鳍状肢之前调用的函数,将每个球设置在页面上的随机 x-y 起始位置。 我建议给每个球相同的ball类,这样你就可以做这样的事情

`$.('.ball').each(function(index, ball){
//do something with ball
});`

为此,您将需要http://api.jquery.com/each/http://api.jquery.com/css/和javascript math.random()http://www.w3schools.com/jsref/jsref_random.asp(也许不会让随机超过你可以用$(document).height() and $(document).width()获得的可见页面的尺寸)

同样不要忘记,根据用例,他们可能需要绝对的CSS定位。

然后看看另一个函数,在这种情况下你可以循环flipper它将循环穿过each()球,并在随机距离内对随机方向进行动画处理,然后根据你想要什么再次返回。