在html / javascript中改组三个图像的位置

时间:2014-02-01 10:46:54

标签: javascript jquery html

我试图以随机顺序实现随机播放三张图像 这是我迄今取得的成就 shuffle jsfiddle

我想随便互相洗牌

$(document).ready(function () {
            shuffle(1);
        });
        var shipsArray = new Array();
        shipsArray = ["1", "2", "3"];
        function shuffle(level) {

            for (i = 0; i < 30; i++) {
                var j = i % 3;

                var favorite = shipsArray[Math.floor(Math.random() * shipsArray.length)];
                if (j != favorite) {
                    var newposition = $("#ship" + shipsArray[favorite]).position();
                    var tempPosition = $("#ship" + shipsArray[j]).position();
                    $("#ship" + shipsArray[j]).animate({ "left": newposition.left, "top": newposition.top });
                    $("#ship" + shipsArray[favorite]).animate({ "left": tempPosition.left, "top": tempPosition.top });
                }

            }
        }

1 个答案:

答案 0 :(得分:2)

这是我的最终解决方案(有点)。

我不得不使用setTimeout()来做正确的时机。

JSFiddle

HTML(未更改,仅为完整性)

<div id="MainDiv">
    <img id="ship1" src="http://cdn-img.easyicon.net/png/154/15462.png" />
    <img id="ship2" src="http://cdn-img.easyicon.net/png/154/15462.png" />
    <img id="ship3" src="http://cdn-img.easyicon.net/png/154/15462.png" />
</div>

CSS(也未更改)

#MainDiv {position:absolute;}
#MainDiv img {position:absolute;}
#ship1 {top:10px; left:200px;}
#ship2 {top:210px; left:0px;}
#ship3 {top:210px; left:400px;}

<强> JS

var ships = [] /* array of ships */
var time_anim = 500 /* anim time */

$(document).ready(function () {
    ships = $("#MainDiv img"); /* find ships */
    shuffle(6); /* wheeee */
});

function shuffle(level) {
    /* do the animation */
    var c = randInt(2, 3)
    cycle(getElements(ships, c))

    if (level > 1) {
        setTimeout(function () {
            shuffle(level - 1)
        }, time_anim)
    }
}

function randInt(min, max) {
    /* get random integer */
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function cycle(items) {
    /* cycle ships in array */
    var pos0 = $(items[0]).position()

    for (i = 1; i < items.length; i++) {
        var sh = items[i];
        var shp = $(sh).position();

        $(items[i - 1]).animate({
            "left": shp.left,
                "top": shp.top
        }, time_anim);
    }

    $(sh).animate({
        "left": pos0.left,
            "top": pos0.top
    }, time_anim);
}

function getElements(arr, n) {
    /* Get n random elements from array */
    var used = []
    var result = []

    while (result.length < n && result.length < arr.length) {
        var i = randInt(0, arr.length - 1)
        if (jQuery.inArray(i, used) !== -1) {
            continue;
        }

        used.push(i)
        result.push(arr[i])
    }

    return result;
}

(也许它可以做得更容易,但是没有 - 它有效。