[英]Random background image every 5 seconds?
我基本上找到了此代碼,並嘗試對其進行了一些更改。 我嘗試使用圖像代替顏色,但是效果不是很好。 我已經檢查了其他類似的問題,但是無論如何,它並沒有給我一直在尋找的幫助。
正如您在代碼中看到的那樣,它每隔5000毫秒隨機更改backgroundColor,我想知道如何使其隨機更改圖片(背景圖像)而不是顏色?
<script type="text/javascript">
function setbackground()
{
window.setTimeout( "setbackground()", 5000); // 5000 milliseconds delay
var index = Math.round(Math.random() * 9);
var ColorValue = "FFFFFF"; // default color - white (index = 0)
if(index == 1)
ColorValue = "FFCCCC"; //peach
if(index == 2)
ColorValue = "CCAFFF"; //violet
if(index == 3)
ColorValue = "A6BEFF"; //lt blue
if(index == 4)
ColorValue = "99FFFF"; //cyan
if(index == 5)
ColorValue = "D5CCBB"; //tan
if(index == 6)
ColorValue = "99FF99"; //lt green
if(index == 7)
ColorValue = "FFFF99"; //lt yellow
if(index == 8)
ColorValue = "FFCC99"; //lt orange
if(index == 9)
ColorValue = "CCCCCC"; //lt grey
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
}
</script>
<body onload="setbackground();">
您可以這樣操作:
<script type="text/javascript">
function setbackground()
{
window.setTimeout( "setbackground()", 5000); // 5000 milliseconds delay
var index = Math.round(Math.random() * 9);
var ImagePath = "image0.jpg"; // default image
if(index == 1)
ImagePath = "image1.jpg";
if(index == 2)
ImagePath = "image2.jpg";
if(index == 3)
ImagePath = "image3.jpg";
if(index == 4)
ImagePath = "image4.jpg";
if(index == 5)
ImagePath = "image5.jpg";
if(index == 6)
ImagePath = "image6.jpg";
if(index == 7)
ImagePath = "image7.jpg";
if(index == 8)
ImagePath = "image8.jpg";
if(index == 9)
ImagePath = "image9.jpg";
document.getElementsByTagName("body")[0].style.backgroundImage="url('"+ ImagePath+ "')"
}
</script>
<body onload="setbackground();">
這是一種簡單的方法:
function setBackground(urls, targetId) {
setInterval(function() {
var index = Math.floor(Math.random() * (urls.length));
var target = document.getElementById(targetId);
target.style.backgroundImage = "url(" + urls[index] + ")";
}, 5000);
}
其中urls
是圖像url的數組,而targetId
是要更改其background-image
屬性的容器的ID。
JSFiddle上的示例 (帶有小貓)
- 編輯 -
請記住,在加載新圖像時,背景(在背景圖像后面)是可見的。 為了說明這一點,我將background-color
設置為紅色。 當新圖像開始加載時,您會看到紅色閃爍(具有諷刺意味的是符合小貓主題)。
-編輯2--
我重新閱讀了您的問題,看來您想更改正文的背景圖像。 上面的功能(和JSFiddle中的功能)適用於目標ID。 如果要在主體上使用它,則可以為主體指定一個ID,然后以主體的ID作為參數運行該函數。 或者您可以使用以下命令:
function setBackground(urls) {
setInterval(function() {
var index = Math.floor(Math.random() * (urls.length));
var target = document.getElementsByTagName("body")[0];
target.style.backgroundImage = "url(" + urls[index] + ")";
}, 5000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.