如何在高滑道画廊中随机化图像而不重复?

时间:2012-08-12 06:48:43

标签: javascript

到目前为止,我已经完成了将随机化与我的高流失画廊相结合的出色工作。但是现在我正试图让它们不再重复。有什么建议?我看了几篇其他帖子,但似乎无法正确地将它应用于我的代码。我还在学习;你必须原谅我。

这是我的头像代码(javascript):

var gallery = new Array();
gallery[0] = new Array("earlywork001.jpg","earlywork002.jpg","earlywork003.jpg");

function pickImageFrom(whichGallery)
{
var idx = Math.floor(Math.random() * gallery[whichGallery].length);
document.write('<a href="images/earlywork/' + gallery[whichGallery][idx] + '" class="highslide" onclick="return hs.expand(this, config1 )"><img src="images/earlywork/' + gallery[whichGallery][idx] + '" width="140" height="140"></a>');
}

这是我的身体代码(我只放3个让它变得简单,但我实际上有50个图像):

<div class="highslide-gallery"><script language="javascript">pickImageFrom(0);</script>
    <span class="highslide-heading"><i>Copyright © 2012 KD Neeley</i></span></div>

<div class="highslide-gallery"><script language="javascript">pickImageFrom(0);</script>
    <span class="highslide-heading"><i>Copyright © 2012 KD Neeley</i></span></div>

<div class="highslide-gallery"><script language="javascript">pickImageFrom(0);</script>
    <span class="highslide-heading"><i>Copyright © 2012 KD Neeley</i></span></div>

2 个答案:

答案 0 :(得分:0)

您可以将所有图像添加到js数组中。 创建一个从数组中获取img的函数。 使用该功能决定要显示的图像。

var images = ["img1.jpg","img2.jpg"];
var shownImages = [];

function randomimg(images,shownImages){

   //select a random number from with in the range of the image array
   rand = Math.floor((Math.random()*images.length())+1);
   //store the displayed image in the shown array and remove it from images
   shownImages.unshift(images.splice(rand,rand+1));

   //if the image array is empty 
   //I guess we would like to show the images over again so resetit
   //The commented out part is only necessary if you want to show
   //images in a loop
   /*if(images.length == 0){
     images = shownImages;
     shownImages = [];
   }*/

   //return the image to show this time.
   return shownImages[0];
}

答案 1 :(得分:0)

将shuffle添加到数组原型

Array.prototype.shuffle=function(){
   var i = len = this.length;       
   while (i--) {
      var r = Math.round(Math.random(len));
      var t = this[i];
      this[i] = this[r];
      this[r] = t;
   }
   return this;
}

然后你可以将shuffle方法用于任何数组:

gallery.shuffle(); // this shuffles the array

演示: http://jsfiddle.net/W75Kw/1/

按要求更新:使用您发布的代码:

var gallery = new Array();
gallery[0] = new Array("earlywork001.jpg","earlywork002.jpg","earlywork003.jpg");
gallery[0].shuffle(); // randomize array

function pickImageFrom(whichGallery) {
  var img = gallery[whichGallery].pop(); // extracts element from array
  document.write('<a href="images/earlywork/' + img + '" class="highslide" onclick="return hs.expand(this, config1 )"><img src="images/earlywork/' + img + '" width="140" height="140"></a>');
}