日期:2014-05-16  浏览次数:20398 次

JS 刷新随机控制DIV的的位置
<div class="box_0531" id="box_0531">
<div class="cont1" id="cont1">
</div>
<div class="cont2" id="cont2">
</div>
<div class="cont3" id="cont3">
</div>
<div class="cont4" id="cont4">
</div>
</div>

想JS 控制cont1到cont4下的多个DIV的位置随机变换,
比如说,刷新一次后可以这样,
<div class="box_0531" id="box_0531">
<div class="cont3" id="cont3">
</div>
<div class="cont1" id="cont1">
<div class="cont4" id="cont4">
</div>
</div>
<div class="cont2" id="cont2">
</div>
</div>
再刷新就可以变位置,
<div class="box_0531" id="box_0531">
<div class="cont2" id="cont2">
</div>
<div class="cont1" id="cont1">
</div>
<div class="cont4" id="cont4">
</div>
<div class="cont3" id="cont3">
</div>

</div>
请问JS如何实现?

------解决方案--------------------
cont1到cont4 还可以 相互嵌套?
------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload = function() {
    var box = document.getElementById('box_0531');
    var obj = box.getElementsByTagName('div'), ar = [];
    for (var i = 0; i < obj.length; i ++) ar.push(obj[i]);
    function sortRandom(a, b) { return Math.random() - 0.5; }
    ar.sort(sortRandom);
    box.innerHTML = '';
    for (var i = 0; i < ar.length; i ++) box.appendChild(ar[i]);
}
</script>
</head>

<body>
<div class="box_0531" id="box_0531">
  <div class="cont1" id="cont1">CONT1</div>
  <div class="cont2" id="cont2">CONT2</div>
  <div class="cont3" id="cont3">CONT3</div>
  <div class="cont4" id="cont4">CONT4</div>
</div>
</body>
</html>

------解决方案--------------------
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload = function() {
    var box = document.getElementById('box_0531');
    var obj = box.getElementsByTagName('div'), ar = [];
    for (var i = 0; i < obj.length; i ++) ar.push(obj[i]);
    function sortRandom(a, b) { return Math.random() - 0.5; }
    ar.sort(sortRandom);
    //box.innerHTML = '';
    for (var i = 0; i < ar.length; i ++) box.appendChild(ar[i]);
}
</script>
</head>

<body>
<div class="box_0531" id="box_0531">
  <div class="cont1" id="cont1">CONT1</div>
  <div class="cont2" id="cont2">CONT2</div>
  <div class="cont3" id="cont3">CONT3</div>
  <div class=&qu