方法1
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
window.onload=function(){
var arr = new Array(1,2,3,4,5,6);
var ul = document.getElementsByTagName('ul')[0];
var len1 = arr.length;
var len = len1;
var index = parseInt(Math.random()*len1);
for(var i=0;i<len1;i++){
ul.appendChild(ul.children[index]);
arr.pop(index);
len = arr.length;
index = parseInt(Math.random()*len);
}
};
</script>
</head>
<body>
<ul>
<li>苹果</li>
<li>桔子</li>
<li>香蕉</li>
<li>石榴</li>
<li>桃子</li>
<li>菠萝</li>
</ul>
</body>
</html>
方法2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload = function(){
var arr = [['<li>1</li>'],['<li>2</li>'],['<li>3</li>'],['<li>4</li>'],['<li>5</li>'],['<li>6</li>']];
var result = '';
var len = arr.length;
for(var i=0;i<len ;i++){
var rand = parseInt(arr.length*Math.random());
result += arr[rand];
arr.splice(rand,1);
}
document.getElementsByTagName("ul")[0].innerHTML= result ;
};
//arr 数组就是ul里的内容组成的字符串数组
</script>
</head>
<body>
<ul></ul>
</body>
</html>
方法3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.onload = function(){
var ul = document.getElementsByTagName("ul")[0];
var lis = document.getElementsByTagName("li");
var arr = [];
for(var i = 0; i < lis.length; i++){
arr.push(lis[i]);
}
arr.sort(function(a,b){
/*var rand = Math.random();
if(rand > 0.5) {
return 1;
}else if(rand < 0.5){
return -1;
} else {
return 0;
}*/
return Math.random()>.5 ? -1 : 1;
//通过随机产生0到1的数,然后判断是否大于0.5从而影响排序,产生随机性的效果。
});
for(var i = 0; i < arr.length; i++){
ul.appendChild(arr[i]);
}
}
</script>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
</html>