Javascript:为每个问候消息显示不同的颜色

时间:2017-10-15 21:37:27

标签: javascript

在我的javascript程序中,我试图为每个问候语消息生成不同的背景颜色,为此我使用了randomColor来应用背景颜色,但它不起作用。谁能告诉我哪里错了。

代码:

<!DOCTYPE html>
<html>
<head>
    <title>trail6</title>
</head>
<body>

    <p id="demo"></p>

    <script>

    var today = new Date()
    var curHr = today.getHours()

    if (curHr >= 0 && curHr < 6) {
        document.getElementById("demo").innerHTML = 'What are you doing that early?';
    } else if (curHr >= 6 && curHr < 12) {
        document.getElementById("demo").innerHTML = 'Good Morning';
    } else if (curHr >= 12 && curHr < 17) {
        document.getElementById("demo").innerHTML = 'Good Afternoon';
    } else {
        document.getElementById("demo").innerHTML = 'Good Evening';
    }

    var colors = ["#D3FFA3", "#FFF8A7", "#FFBC98", "#FF9A95","#B6FDFF", "#A8FFC1", "#B6FF99"];
    var randomColor = colors[Math.floor(Math.random() * colors.length)];    
    document.getElementById("demo").style.backgroundColor = colors[randomColor];

</script>

</body>
</html> 

2 个答案:

答案 0 :(得分:2)

当您指定randomColor时,您已经已经访问colors数组; randomColor设置为十六进制代码。

因此,您只需使用document.getElementById("demo").style.backgroundColor = randomColor而不是document.getElementById("demo").style.backgroundColor = colors[randomColor]直接将背景颜色设置为存储的十六进制代码。

这可以在以下示例中看到:

&#13;
&#13;
var today = new Date()
var curHr = today.getHours()

if (curHr >= 0 && curHr < 6) {
  document.getElementById("demo").innerHTML = 'What are you doing that early?';
} else if (curHr >= 6 && curHr < 12) {
  document.getElementById("demo").innerHTML = 'Good Morning';
} else if (curHr >= 12 && curHr < 17) {
  document.getElementById("demo").innerHTML = 'Good Afternoon';
} else {
  document.getElementById("demo").innerHTML = 'Good Evening';
}

var colors = ["#D3FFA3", "#FFF8A7", "#FFBC98", "#FF9A95", "#B6FDFF", "#A8FFC1", "#B6FF99"];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
document.getElementById("demo").style.backgroundColor = randomColor;
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;

希望这有帮助! :)

答案 1 :(得分:1)

看最后一行

document.getElementById(“demo”)。style.backgroundColor = colors [randomColor];

像这样改变

document.getElementById(“demo”)。style.backgroundColor = randomColor;

刚刚测试过,似乎工作正常

debugger snapshot