繁体   English   中英

如何在高幻灯片库中随机化图像而不重复?

[英]How can I randomize images without repeat in a highslide gallery?

到目前为止,我在将随机化与我的高幻灯片画廊集成方面做得非常出色。 但是现在我正在尝试使其不再重复。 有什么建议么? 我看过其他几篇文章,但似乎无法正确地将其应用于我的代码。 我还在学习; 你得原谅我

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

您可以将所有图像添加到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];
}

向数组原型添加随机播放

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>');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM