[英]Background Color Change onload JavaScript+Html
我正在嘗試編寫我自己的網站,但是我有一個想法,每次加載/刷新頁面時,網站都會隨機更改為一組背景顏色(但不會背靠背重復相同的顏色)。 我記得我在學校時做過與此非常相似的事情,但我不太記得它是如何完成的。
到目前為止,這就是我所擁有的,我已經擺弄了大約一天,只是無法弄清楚我錯過了什么。
任何幫助將不勝感激。
<html>
<head>
<script type="text/javascript">
<!--
var color = new Array();
color[0] = "#CC99FF";
color[1] = "#FF99CC";
color[2] = "#FF9999";
color[3] = "#FFCC99";
color[4] = "#FFFF99";
color[5] = "#CCFF99";
color[6] = "#99FF99";
color[7] = "#99FFCC";
color[8] = "#66FFFF";
color[9] = "#66CCFF";
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor];
}
--!>
</script>
</head>
<body onload="changeColor()">
</body>
</html>
我注意到你的問題有第二部分,那就是不要重復相同的顏色兩次。 由於您是在重新加載時執行此操作,因此它變得有點棘手,因為您不能將最后一種顏色存儲在一個簡單的變量中。
為此,我決定使用localStorage 。 我還利用了其他一些答案,其中提到您需要在 body 元素上使用 style 屬性。
這是解決方案的小提琴,代碼如下:
如前所述,您需要使用 style 屬性來設置背景顏色:
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
然后,您需要繼續查找上次運行中未使用的索引:
首先,我獲取當前存儲的索引,如果不存在則獲取 -1。
var lastColorIndex = localStorage.getItem('lastColorIndex') || -1;
然后在兩個索引不相等或隨機顏色為 -1 時設置循環(這是在初始頁面加載時)。 請注意,我們使用==
進行“真實”檢查,因為localStorage
將返回一個字符串,而Math.random()
返回一個數字;
while(lastColorIndex == randomColor || randomColor === -1)
最后,將 randomColor 值設置到本地存儲中。
localStorage.setItem('lastColorIndex',randomColor);
現在都在一起了:
function changeColor()
{
var lastColorIndex = localStorage.getItem('lastColorIndex') || -1;
var randomColor = -1;
while(lastColorIndex == randomColor || randomColor === -1) {
randomColor = Math.floor(Math.random() * color.length);
console.log('LastIndex: ' + lastColorIndex + ',RandomColor: ' + randomColor);
};
localStorage.setItem('lastColorIndex',randomColor);
//console.log(randomColor);
console.log(color[randomColor]);
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
};
你必須了解你的體型:
function changeColor() {
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor];
}
你可以像這樣改變背景顏色
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.background = color[randomColor];
}
您沒有正確訪問背景顏色屬性。請以這種方式使用它。
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor]; //THIS IS IMP
}
看看這個小提琴(單擊“運行”幾次以模擬重新加載):
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
console.log(color[randomColor]);
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
};
您應該在窗口或文檔“onload”中調用“changeColor”。
我在一個主題中找到了一個代碼希望這對你有幫助
$('.animated-bg').each(function(){
var $this = $(this),
colors = ['#ec008c', '#00bcc3', '#5fb26a', '#fc7331'];
setInterval(function(){
var color = colors.shift();
colors.push(color);
$this.animate({backgroundColor: color}, 2000);
},4000);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.