洗牌divs,但显示数量有限 [英] shuffle divs but show limited number of them

查看:91
本文介绍了洗牌divs,但显示数量有限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$

我使用这段代码每n秒洗牌一次div元素。 p $ p> var parent = $(#shuffle);
var divs = parent.children()。slice();

setInterval(function(){
var clone = divs.slice(); //< - clone,因为拼接会修改数组
while(clone.length){
parent.append(clone.splice(Math.floor(Math.random()* clone.length),1)[0]);
}
},2000); //< - 每2秒洗牌

http://jsfiddle.net/yxBhH/1/
我对Javascript解决方案感兴趣

解决方案

这是一个简单的解决方案。



在每个间隔中,清除所有元素,然后添加 n 从列表中随机选取的元素。

  var populateParent =(function (){
var parent = $(#shuffle);
var divs = parent.children()。slice();
返回函数(){
parent。 empty();
var clone = divs.slice();
for(var i = 0; i< 2& i< divs.length; ++ i){
parent.append(clone.splice(Math.floor(Math.random()* clone.length),1)[0]);
};
}
})( );

populateParent();
setInterval(populateParent,2000);

http://jsfiddle.net/rv7zpd07/5/


I'm using this code to shuffle elements of div every n seconds .. is there a way to display only 2 elements (for example ) with each shuffle ?

var parent = $("#shuffle");
var divs = parent.children().slice();

setInterval(function() {
    var clone = divs.slice(); // <-- clone, since splice modifies array
    while (clone.length) {
        parent.append(clone.splice(Math.floor(Math.random() * clone.length), 1)[0]);
    }
}, 2000); // <-- shuffle each 2 seconds

http://jsfiddle.net/yxBhH/1/ I'm Interested in Javascript solution

解决方案

Here's an easy solution.

On each interval, clear out all of the elements, and then add n elements randomly picked from the list.

var populateParent = (function() {
  var parent = $("#shuffle");
  var divs = parent.children().slice();
  return function() {
    parent.empty();
    var clone = divs.slice();
    for (var i = 0; i < 2 && i < divs.length; ++i) {
      parent.append(clone.splice(Math.floor(Math.random() * clone.length), 1)[0]);
    };
  }
})();

populateParent();
setInterval(populateParent, 2000);

http://jsfiddle.net/rv7zpd07/5/

这篇关于洗牌divs,但显示数量有限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆