我正在尝试编写自己的网站,但是我有一个想法,即每次加载页面时,网站都会随机更改为一组背景颜色(但不会背靠背重复相同的颜色)/刷新。我记得我在学校时做过与此非常相似的事情,但我不太记得它是如何完成的。
这就是我到目前为止所拥有的,我已经摆弄了大约一天,只是无法弄清楚我错过了什么。
如有任何帮助,我们将不胜感激。
<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 属性。
这是一个Fiddle解决方案和代码如下:
如前所述,您需要使用样式属性来设置背景颜色:
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
然后,您需要继续寻找上次运行时未使用的索引:
首先,我获取当前存储的索引,如果它不存在则为 -1。
var lastColorIndex = localStorage.getItem('lastColorIndex') || -1;
然后在两个索引不相等或随机颜色为 -1 时设置执行循环(这是针对初始页面加载)。请注意,我们正在使用 ==
进行“真实”检查,因为 localStorage
将返回一个字符串,而 Math.random()
将返回一个数字;
while(lastColorIndex == randomColor || randomColor === -1)
最后,将随机颜色值设置到本地存储。
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];
};
关于javascript - 背景颜色改变 onload JavaScript+Html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31186242/