【问题标题】:Javascript background changing based on functionJavascript背景根据功能改变
【发布时间】:2015-04-14 22:05:20
【问题描述】:
当我单击一个按钮时,我必须模拟一个在 0 到 37 之间选择随机数的函数。如果是偶数,则背景为红色。如果它很奇怪,背景是黑色的。初始背景为浅蓝色。这是我到目前为止所拥有的,它不起作用。
<html>
<head>
<title>Wheel</title>
<script type="text/javascript">
var currentNum = wheelspins();
document.body.style.backgroundColor = "#00ffff";
function wheelspins()
{
return Math.floor(Math.random() * 37);
if(currentNum % 2 == 0){
style.backgroundColor="#FF0000";
}
else if(currentNum %2 == 1){
style.backgroundColor="#000000";
}
}
</script>
</head>
<body>
<form>
<input type="text" name="Number" value="" id="wheelspins()" size="10"/>
<input type="button" value="Spin Wheel" onclick="document.getElementById('wheelspins()').value=wheelspins();"/>
</form>
</body>
</html>
【问题讨论】:
标签:
javascript
button
random
background
click
【解决方案1】:
我看到两个可能的问题。首先,评估代码永远不会运行,因为函数在背景可以更改之前返回。其次,你应该在函数中写document.body.style.background而不是style.background。将您的 wheelspins() 函数更改为这样,它应该可以工作:
function wheelspins()
{
//If you return here, then the rest of the function won't get run
currentNum = Math.floor(Math.random() * 37);
if(currentNum % 2 == 0){
document.body.style.backgroundColor="#FF0000";
}
else if(currentNum %2 == 1){
document.body.style.backgroundColor="#000000";
}
return currentNum
}
【解决方案2】:
您的 javascript 存在一些问题。例如,当您返回随机数时,您的 wheelspins 函数的 if-else 块永远不会到达(也许您缺少括号?)
此外,还不清楚您要使用 <input type="text" /> html 完成什么。你想那里返回生成的随机数吗?
您还只需要评估您的数字是偶数(还是奇数)。这是一个例子:
function wheelSpin(){
var random = Math.floor(Math.random() * 37);
if(random % 2 == 0){
document.body.style.backgroundColor = "#FF0000";
} else {
document.body.style.backgroundColor = "#000000";
}
}
body{
background-color: #00ffff;
}
<button onclick="wheelSpin()">Spin Wheel</button>