如何指定此随机图像脚本

时间:2014-03-12 21:10:25

标签: javascript

我有这个javascript在点击时显示随机图像:

function pickimg(){
var imagenumber = 4 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "images/1.png"
images[2] = "images/2.png"
images[3] = "images/3.png"
images[4] = "images/4.png"
var image = images[rand1]
document.randimg.src = image

有没有办法确保同一张图片连续两次不显示?

1 个答案:

答案 0 :(得分:0)

这个小小的算法怎么样?

  1. 将最后使用的图像存储在数组的插槽0中
  2. 选择索引大于0的随机图像。
  3. 显示
  4. 将其替换为插槽0中的图像
  5. 使用Javascript:

     images = new Array();
     images[0] = "images/1.png" //will be that last used image
     images[1] = "images/2.png"
     images[2] = "images/3.png"
     images[3] = "images/4.png"
     function pickimg(){
         var randomnumber = Math.random();
         // pick a random number from 1 to LENGTH (3)
         var rand1 = Math.round( (images.length-1) * randomnumber)+1;
         var image = images[rand1]; //get the image
    
        // switch so that the random image will be in the used
        // images slot (slot 0)
        images[rand1] = images[0] 
        images[0] = image 
    
        document.randimg.src = image
    }