2012-08-11 98 views
1

嘿,我一直在試圖在瀏覽器中做一個沒有任何空白的全屏圖像,並且每次刷新瀏覽器時都會有一個隨機圖像,我知道必須有一種方法可以用圖像數組來做到這一點?任何人都可以幫助我不知道如何開始。 到目前爲止,這是我想出了:瀏覽器刷新時出現全屏圖像隨機Javascript

var images=new Array(); 
    images[0]="images/image1.jpg"; 
    images[1]="images/image2.jpg"; 
    images[2]="images/image3.jpg"; 
    images[3]="images/image4.jpg"; 

請幫幫我!我真的很喜歡它!

+0

如果你還沒有,你需要一些CSS來使圖像全屏顯示。 – starbeamrainbowlabs 2012-08-12 09:16:40

回答

0

像這樣

var srcs = {"images/pic1.jpg","images/pic2.jpg","images/pic3.jpg"}; 
    var index= Math.floor (Math.random() * 3); 
    imagethingy.src = srcs[index]; 


document.body.style.backgroundImage = "url(" + imagethingy.src = srcs[index]; + ")"; 

<html> 
<head> 
<script type="text/javascript"> 
function randomize(min, max) { 
    if (!min) 
     min = 0; 
    if (!max) 
     max = 1; 
    return Math.floor(Math.random()*(max+1)+min); 
} 
function randomBg() { 
    var bgs = new Array(); 
    // I took these images from a site with a similar script already only to get example images 
    // I wrote this script myself 
    bgs.push("http://javascript.internet.com/img/backgrounds/wood.gif"); 
    bgs.push("http://javascript.internet.com/img/backgrounds/paper.gif"); 
    bgs.push("http://javascript.internet.com/img/backgrounds/clouds.gif"); 
    bgs.push("http://javascript.internet.com/img/backgrounds/faces.gif"); 
    bgs.push("http://javascript.internet.com/img/backgrounds/marble.gif"); 
    document.body.style.backgroundImage = "url(" + bgs[randomize(0, bgs.length-1)] + ")"; 
} 
</script> 
</head> 
    <body onLoad="randomBg()" style="text-align:center;"> 
<div>some text</div> 
    </body> 
</html> 
+0

如果min爲0,那麼!min的計算結果爲真,這有點奇怪。同樣,如果max爲0,則它​​變爲1.我建議明確測試未定義的值,並測試min AlanFoster 2012-08-11 20:41:16