问题描述
<$
我使用这段代码每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秒洗牌
我对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);
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,但显示数量有限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!