如何随机化图像顺序?

时间:2013-02-20 01:04:29

标签: javascript html

第I页reference

加载图片的部分:

<div id="lighttable">

<img src="http://throwingupthew.com/girls/01.jpg" alt="01" />
<img src="http://throwingupthew.com/girls/02.jpg" alt="02" />
<img src="http://throwingupthew.com/girls/03.jpg" alt="03" />

etc....

</div>

我如何随机化图像的顺序? 请记住,我不知道在index.html中放置任何代码/答案的位置

谢谢。

1 个答案:

答案 0 :(得分:0)

将您的HTML更改为:

<div id="lighttable">

<img id="girl1" src="" alt="01" />
<img id="girl2" src="" alt="02" />
<img id="girl3" src="" alt="03" />

etc....

</div>

将此放在页面的</head>标记

之前
<script type="text/javascript">
var array = ['http://throwingupthew.com/girls/01.jpg','http://throwingupthew.com/girls/02.jpg','http://throwingupthew.com/girls/03.jpg'];
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}
var shuffled_images = shuffle(array);
for(var i=0;i<3;i++) {
document.getElementById('girl' + (i+1)).src = shuffled_images[i] ;
}
</script>

感谢此页面Randomizing(Shuffling) an Array,我能够为您制作此脚本:)

这是工作JSFiddle:)