2011-10-20 44 views
0

我有一个脚本运行在我的网页上来更改图像。我想在同一页面的其他地方重复使用6次,但当我重复使用时,它不会起作用。问题与Javascript图像转换器

var delay = 2000 //set delay in miliseconds 
    var curindex = 0 

    var randomimages = new Array() 

    randomimages[0] = "hhh200.jpg" 
    randomimages[1] = "ray200.jpg" 

    var preload = new Array() 

    for (n = 0; n < randomimages.length; n++) { 
     preload[n] = new Image() 
     preload[n].src = randomimages[n] 
    } 

    document.write('<img name="defaultimage" src="' + randomimages[Math.floor(Math.random() * (randomimages.length))] + '">') 

    function rotateimage() { 

     if (curindex == (tempindex = Math.floor(Math.random() * (randomimages.length)))) { 
      curindex = curindex == 0 ? 1 : curindex - 1 
     } else curindex = tempindex 

     document.images.defaultimage.src = randomimages[curindex] 
    } 

    setInterval("rotateimage()", delay) 

任何人都可以看到为什么它不工作?

+3

需要比“但它不会工作”,以帮助更多的细节。 –

+0

你的代码正在使用我的FF 7.0.1 – user973254

+0

是的,我知道它的作品,但是当我复制并粘贴到页面上的其他地方时,所有图像都不会改变?他们都留在文具 –

回答

0

如果您只是在页面上的其他地方复制并粘贴它,那么您将重写变量值,并且您将同时为这两个图像命名,所以这些问题就是2个问题。你应该把它放在函数中,并在你想要的2个地方调用该函数。

试试这个。

function randomImage(randomImages, imageName) { 
    var delay = 2000 //set delay in miliseconds 
    var curindex = 0 

    var preload = new Array() 

    for (n = 0; n < randomImages.length; n++) { 
     preload[n] = new Image() 
     preload[n].src = randomImages[n] 
    } 

    document.write('<img name="' + imageName + '" src="' + randomImages[Math.floor(Math.random() * (randomImages.length))] + '">'); 

    function rotateimage() { 
     var tempindex = Math.floor(Math.random() * (randomImages.length)); 
     if (curindex == tempindex) { 
      curindex = curindex == 0 ? 1 : curindex - 1 
     } else curindex = tempindex 

     document.images[imageName].src = randomImages[curindex]; 
    } 

    setInterval("rotateimage()", delay); 
} 



// and then to use it, create your image arrays outside of the function, and call the function. 

var images1 = new Array(); 
images1[0] = "hhh200.jpg"; 
images1[1] = "ray200.jpg"; 

var images2 = new Array(); 
images2[0] = "hhh200.jpg"; 
images2[1] = "ray200.jpg"; 


randomImage(images1, 'imageOneName'); 



randomImage(images2, 'imageTwoName'); 

我还没有测试过这个代码,但这是你应该遵循的一般想法。