0

到目前为止,我在将随机化与我的 highslide 画廊集成方面做得非常出色。但现在我正努力做到这一点,以免他们重复。有什么建议么?我查看了其他几篇文章,但似乎无法将其正确应用于我的代码。我还在学习; 你必须原谅我。

这是我的头代码(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>
4

2 回答 2

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];
}
于 2012-08-12T08:05:51.230 回答
0

将随机播放添加到数组原型

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>');
}
于 2012-08-12T08:14:18.997 回答