【问题标题】:How Do I Randomize the Order of the Images?如何随机化图像的顺序?
【发布时间】:2013-02-04 21:44:03
【问题描述】:

第一页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 中放置任何代码/答案的位置

谢谢。

【问题讨论】:

  • 首先做一些研究:stackoverflow.com/questions/5329201/…
  • 你想用 JavaScript 随机化它们还是...?
  • 我想以最简单的方式随机化。除了调整值以改变结果之外,我对 html/javascript 编码一无所知。
  • 也许随机化是在 initphotos 函数中完成的?

标签: javascript html


【解决方案1】:

把你的 HTML 改成这样:

<div id="lighttable">

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

etc....

</div>

把它放在你页面的&lt;/head&gt;标签之前

<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 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2016-01-24
    • 1970-01-01
    • 2020-09-06
    • 2012-09-21
    • 2023-03-14
    • 2021-02-16
    相关资源
    最近更新 更多