JQuery - Randomise元素在容器内的绝对位置和旋转

时间:2015-02-13 03:59:14

标签: javascript jquery css3

我有以下内容在容器div中随机化div。正如您在fiddle中看到的那样正常工作。

<div id='draggables_container'>
    <div class='draggable' id='d1'></div>
    <div class='draggable' id='d2'></div>
    <div class='draggable' id='d3'></div>
    <div class='draggable' id='d4'></div>
    <div class='draggable' id='d5'></div>
</div>

function randomiseDraggables(){
var parent = $("#draggables_container");
var divs = parent.children();
while (divs.length) {
    parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
}

如何更改此元素以使元素在容器内具有随机绝对位置(它们当前设置为float:left)并且随机旋转并且最好不相互重叠?

1 个答案:

答案 0 :(得分:1)

如上所述的解决方案:

HTML

<div id='draggables_container'>
    <div class='draggable' id='d1'></div>
    <div class='draggable' id='d2'></div>
    <div class='draggable' id='d3'></div>
    <div class='draggable' id='d4'></div>
    <div class='draggable' id='d5'></div>
</div>

CSS

#draggables_container {
    float:left;
    height:auto;
    width:600px;
    border: 1px solid #6ac1cb;
    border-radius: 4px;
}
.draggable {
    float:left;
    height:120px;
}
#d1 {
    width:20%;
    background-image: url(http://130.95.21.121/karyotypes/trisomy_21/images/1_a.png);
    background-repeat:no-repeat;
}
#d2 {
    width:20%;
    background-image: url(http://130.95.21.121/karyotypes/trisomy_21/images/1_b.png);
    background-repeat:no-repeat;
}
#d3 {
    width:20%;
    background-image: url(http://130.95.21.121/karyotypes/trisomy_21/images/2_a.png);
    background-repeat:no-repeat;
}
#d4 {
    width:20%;
    background-image: url(http://130.95.21.121/karyotypes/trisomy_21/images/2_b.png);
    background-repeat:no-repeat;
}
#d5 {
    width:20%;
    background-image: url(http://130.95.21.121/karyotypes/trisomy_21/images/3_a.png);
    background-repeat:no-repeat;
}

jquery的

function randomiseDraggables() {
    var parent = $("#draggables_container");
    var divs = parent.children();
    divs.each(function() {
        var rt = (Math.floor(Math.random() *359));
        var rn = (Math.floor(Math.random() *50));
        $(this).css({'transform':'rotate(' + rt + 'deg)','background-position' : '0% ' + rn + '%'});
        });
    while (divs.length) {
        parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
}

randomiseDraggables();

$(".draggable").draggable({
  stack: '#draggables_container div',
  revert: true
});