0

我已经看到了很多与此类似的问题,但我无法找到解决这个特定问题的问题,或者我认为。

我有一个以这种格式构建的页面,它控制网页动态部分的浓度,我想要它做的是随机基于具有“switchme”类的 div。所以基本上我希望所有内容都可以交换,而不会改变“switchme”中的内容,只是它在页面中的位置。我尝试了许多 javascript 和 jquery 脚本,但最终它总是在内部 div 周围移动

<div class= "switchme_container">
<div class = "switchme">
<div>Content</div>
<div>Content</div>
<div>Content</div>
<div>Content</div>
</div>
<div class = "switchme">
<div>Content</div>
<div></div>
<div></div>
<div></div>
</div>
<div class = "switchme">
<div>Content</div>
<div>Content</div>
<div>Content</div>
<div>Content</div>
</div>
</div>

<script>
function shuffle(sj) {              
var replace = $('<div>');
var size = sj.size();

while (size >= 1) {
   var randomize = Math.floor(Math.random() * size);
   var tempdiv = sj.get(randomize);      
   replace.append(tempdiv);        
   sj = sj.not(tempdiv); 

}
$('#switchme_container').html(replace.html() );   
</script>
4

3 回答 3

1

您可以将元素复制switchme到数组中,以更明显的方式将它们打乱,然后将它们推回switchme_container元素中:

var shuffle = function(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
$(".switchme_container").append(shuffle($.makeArray($(".switchme"))));

jsFiddle:http: //jsfiddle.net/D2jxe/2/

jQuery 会自动移动每个元素而不是复制它,除非您在插入之前显式克隆它。

从这里复制的随机播放函数:如何随机播放数组?

于 2012-12-27T18:58:11.690 回答
0

移动某物的一般公式非常简单:

 $newParent.append($thingToMove);

(注意:如果你想放弃事件处理程序/数据,$thingToMove你可以先调用.remove()它。)

如果这对您不起作用,则您需要解决调试问题,但这通常应该有效。

于 2012-12-27T18:40:58.910 回答
0

我已将随机事件附加到按钮单击中,答案嵌入在以下代码的注释中:

​$('#randomize').click(function(ev){
    ev.preventDefault();

    var $sc = $('.switchme_container'),
        contentHolder = [],
        randomIndex;

    // detach .switchme elements from page and add to contentHolder array
    $sc.find('.switchme').each(function(i, el){
        contentHolder.push($(this).detach());
    });

    while (contentHolder.length) {

        // pick a random index of the contentHolder array
        randomIndex = Math.floor(Math.random() * contentHolder.length);

        // append it to the container
        $sc.append(contentHolder[randomIndex]);

        // slice that element out of the contentHolder array
        contentHolder = contentHolder.slice(0, randomIndex)
            .concat(contentHolder.slice(randomIndex + 1, contentHolder.length));
    }
});​​​​​​

看演示

于 2012-12-27T18:54:34.687 回答