2016-12-15 129 views
0

我想找到一種方法,我可以有一個圖像,佔用整個瀏覽器窗口和響應。每次頁面加載時,我都希望背景圖像能夠從我本地選擇的一組照片中進行更改。網頁的隨機背景圖

我已經在這裏嘗試了一些解決方案,但沒有什麼是真正的工作。在HTML我有是:

<div id="container"> 

    <img src="Images/IMG_3764.JPG" alt="An island in the middle of the sea in Turkey" id="backgroundImage"> 

</div> 

的CSS我是:

body { 
margin: 0; 
} 

#container { 
width: 100%; 
height: 100%; 
margin: 0; 
} 

#backgroundImage { 
width: 100%; 
position: fixed; 
top: 0; 
left: 0; 
} 

html, body { 
overflow: none !important; 
overflow-x: none !important; 
overflow-y: none !important; 
} 

一,我已經試過了JS的解決方案是這樣的:

var image = new Array(); 
image[0] = "http://placehold.it/20"; 
image[1] = "http://placehold.it/30"; 
image[2] = "http://placehold.it/40"; 
image[3] = "http://placehold.it/50"; 
var size = image.length 
var x = Math.floor(size*Math.random()) 

$('#backgroundImage').attr('src',image[x]); 
+0

你有你已經試過JavaScript代碼,沒有工作的例子嗎? – Bastiaanus

+0

@Bastiaanus對不起,只是包括了它 –

回答

3

你將需要有存儲在JavaScript像這樣像陣列:

var picArr = [imageSrc1 ,imageSrc2 ,imageSrc3]; 

後,你將需要某種形式的隨機數,符合在上面的數組中,圖像src的數量。

http://www.w3schools.com/jsref/jsref_random.asp

您將使用Math.random()這裏

然後,你需要創建要執行的一種功能,當文檔加載改變上面你的背景的src。

您的最終功能可能是這樣的:

var picArr = ['src0', 'src1', 'src2', 'src3', 'src4', 'src5', 'src6', 'src7', 'src8', 'src9', ]; 

var myNumber = Math.floor((Math.random() * 10) + 1); 

$(document).ready(function() { 
    $("#backgroundImage").attr('src', picArr[myNumber]); 
}); 
+1

感謝所有的回覆,但是這個工作很直接,只需要添加圖像! –

1

使用jQuery你可以做像這樣的東西

See jsfiddle here

var images = ['http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg', 'http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg', 'https://s-media-cache-ak0.pinimg.com/originals/c6/8a/51/c68a5157020c8555ca781839d754a1a0.jpg']; 
 

 
    var randomImage = Math.floor(Math.random() * 3) 
 

 
    $(document).ready(function() { 
 
     $("#container").css("background-image", "url('" + images[randomImage] + "')"); 
 
    })
html, body { 
 
    height: 100%; 
 
} 
 

 
#container { 
 
    background-repeat: no-repeat; 
 
    background-size: cover; 
 
    background-position: center; 
 
    height: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<body> 
 
    <div id="container"></div> 
 
</body>

+0

當我嘗試這個時,我根本沒有在網頁上得到任何東西 –

+0

你需要在$(「body」)中使用正確的ID。css(「background-圖片「,」url('「+ images [randomImage] +」')「);'所以使用'$(」backgroundImage「)。css(」background-image「,」url('「+ images [randomImage] + '')「);' –

+0

你可能想使用'$('#container')' –