每当页面加载或按需刷新时,我都试图为<div>
使用随机颜色,但是它不起作用。我的代码:
<head>
<script type='text/javascript'>//<![CDATA[
document.onload=function(){
var red = Math.floor((Math.random()*256)+0);
var blue = Math.floor((Math.random()*256)+0);
var green = Math.floor((Math.random()*256)+0);
var coloredDiv = document.createElement("div");
document.getElementById("coloredDiv");
coloredDiv.style["background-color"] = 'rgb('+red+','+green+','+blue+')';
}//]]>
</script>
</head>
<body>
<div id="coloredDiv">A div that changes color randomly??!?!?!?!</div>
<a href="javascript:void(0);" onClick="javascript: location.reload(true);">Go again!</a>
</body>
最佳答案
您可以使用以下任一选项设置background-color
:
选项1:
window.onload=function(){
var red = Math.floor((Math.random()*256)+0);
var blue = Math.floor((Math.random()*256)+0);
var green = Math.floor((Math.random()*256)+0);
var coloredDiv =document.getElementById("coloredDiv");
coloredDiv.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';
}
选项2:
coloredDiv.style["backgroundColor"] = 'rgb('+red+','+green+','+blue+')';
要注意的关键是,每当我们使用JS为其中具有连字符的CSS属性设置值时(例如
background-color
),都应删除连字符,并在第二个单词和后续单词的首字母大写。