我正在自学 JavaScript,并尝试在单击按钮时显示随机背景颜色。您可以在下面找到我的代码:
HTML 代码
<!DOCTYPE html>
<html>
<head>
<title>Day 4</title>
<link rel="stylesheet" type="text/css" href="css/foundation.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body id="background">
<div class="row">
<div class="columns small-12">
<ul class="menu">
<li><a href="index.html">Home</a></li>
<li><a href="http://carter3689.tumblr.com/">Blog</a></li>
</ul>
</div>
<div class="row">
<div class="columns small-12">
<div class="container center">
<button id="button"class="button center" onclick="randomColors">Click Here for Color of the Day</button>
</div>
</div>
</div>
</div>
<script src="js/random-color.js"></script>
</body>
</html>
这是我的 CSS 代码:
.background{
background-color: #ECECEA;
}
.text-padding{
padding: 50px;
}
input{
width:250px !important;
padding-left: 50px;
}
.inline{
list-style-type: none;
}
.container{
margin-left: 500px;
}
最后是我的 JavaScript 代码。老实说,这就是我最麻烦的地方。
function randomcolor(){
document.getElementById('background').style.color =randomColors();
}
function randomColors(){
return '#' + Math.floor(Math.random() * 16777215).toString(16);
console.log("I'm working now")
}
您提供的任何帮助都将非常有帮助,因为这对我来说都是一次学习经历。提前致谢!
最佳答案
看起来基本上别人已经回答过了,不过重复也没什么问题。
- 您正在调用
randomColors()
而不是randomcolor()
. - 您确实不应该在 body 标记上使用 getElementById。您只需使用 document.body 即可获取正文。
- 您需要使用
style.background
或style.backgroundColor
获取背景颜色而不是文本颜色。 - 您应该将 js 脚本包含在
<head>
中而不是靠近 html 文档的底部,以确保在调用它们的函数之前加载它们。
关于javascript - 为什么我的 Javascript randomColors 函数在单击按钮时不会生成随机背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34602460/