Chr*_*ris 5 javascript dom dhtml
我对Javascript比较陌生,并且想知道是否有一种快速方法可以随机播放多个<div>标签中包含的内容.例如
<div id='d1'>
<span>alpha</span>
<img src='alpha.jpg'>
</div>
<div id='d2'>
<span>beta</span>
<img src='beta.jpg'>
</div>
<div id='d3'>
<span>gamma</span>
<img src='gamma.jpg'>
</div>
<button onclick='shuffle_content();'>Shuffle</button>
Run Code Online (Sandbox Code Playgroud)
点击按钮后,我希望d1,d2,d3中的内容改变位置(例如,d3可能是第一个,然后是d1,然后是d2).
一种快速移动方法是复制第一个div元素(d1),然后将它放在最后(d3之后),然后删除原始d1.但这并不能真正随意化.它只是让事情进入循环(可能没问题).
任何建议,将不胜感激.谢谢.
Owe*_*wen 20
你喜欢使用像jQuery这样的javascript库吗?这是一个快速的jQuery示例来完成您所追求的目标.对HTML的唯一修改是添加了一个容器元素,如下所示:
<div id="shuffle">
<div id='d1'>...</div>
<div id='d2'>...</div>
<div id='d3'>...</div>
</div>
Run Code Online (Sandbox Code Playgroud)
和javascript:
function shuffle(e) { // pass the divs to the function
var replace = $('<div>');
var size = e.size();
while (size >= 1) {
var rand = Math.floor(Math.random() * size);
var temp = e.get(rand); // grab a random div from our set
replace.append(temp); // add the selected div to our new set
e = e.not(temp); // remove our selected div from the main set
size--;
}
$('#shuffle').html(replace.html() ); // update our container div with the
// new, randomized divs
}
shuffle( $('#shuffle div') );
Run Code Online (Sandbox Code Playgroud)
gil*_*ly3 14
最近的一个问题刚刚结束,但我觉得我得到了比这里更好的答案.这种方法非常直接.复制HTML没有任何问题,因此保留了对DOM,样式,事件处理程序等的更改.
要对某些父元素的所有子元素进行随机播放,请选择一个随机子元素并将其一次附加回父元素,直到所有子元素都被重新附加.
使用jQuery:
var parent = $("#shuffle");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/C6LPY/2
没有jQuery它就像它一样简单:
var parent = document.getElementById("shuffle");
var divs = parent.children;
var frag = document.createDocumentFragment();
while (divs.length) {
frag.appendChild(divs[Math.floor(Math.random() * divs.length)]);
}
parent.appendChild(frag);
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/C6LPY/5/
编辑: 这是代码的细分:
// Create a document fragment to hold the shuffled elements
var frag = document.createDocumentFragment();
// Loop until every element is moved out of the parent and into the document fragment
while (divs.length) {
// select one random child element and move it into the document fragment
frag.appendChild(divs[Math.floor(Math.random() * divs.length)]);
}
// appending the document fragment appends all the elements, in the shuffled order
parent.appendChild(frag);
Run Code Online (Sandbox Code Playgroud)