我的网页上有一个带有彩色背景的div元素。
我希望每次有人加载页面时都会更改颜色。
我在网上找到了这段代码,显然会产生一个随机的十六进制数字:
'#'+Math.floor(Math.random()*16777215).toString(16);
我是JavaScript的新手,因此我正在尝试将我如何实现这一点。
我假设我为随机生成的十六进制分配了一个变量:
bandColor = '#'+Math.floor(Math.random()*16777215).toString(16);
现在我不确定我是否在样式表或html中使用了这个变量(bandColor)。
如果是html,我猜我在JavaScript中做了类似的事情:
$("#band").html(bandColor);
然后在html:
<div id="band">
非常感谢能指出我对错的人!
答案 0 :(得分:2)
尝试元素的style属性,所以:
$("#band").css("background-color", bandColour);
附注:有时您的代码会生成五位或更少的十六进制字符串,例如#9eb8d
。您可以通过left-padding with zeroes:
bandColour = ("000000" + bandColour).slice(-6);
您将在设置背景颜色的语句之前放置。
答案 1 :(得分:1)
纯JavaScript解决方案可以是:
document.getElementById("band").style.background = "blue";
随机颜色:
document.getElementById("band").style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
答案 2 :(得分:1)
用于CSS的外部或嵌入式样式表中的JavaScript。
<!doctype html>
<html>
<head>
<style>
#band{
width: 100%;
height: 500px;
background-color: #123456;
}
</style>
</head>
<body>
<div id="band"><div>
<script>
var bandColour = document.getElementById('band');
bandColour.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
</script>
</body>
</html>