【发布时间】:2018-03-24 19:47:07
【问题描述】:
在我的 JavaScript 程序中,我使用 Math.random() 随机生成了背景颜色。加载页面后,它会自动生成随机颜色。我还创建了链接点击这里。当用户单击链接时,它还应该为我使用 Onclick 函数并添加代码以随机生成颜色生成背景颜色,但是当我单击链接时它不会生成。每次我单击链接时,它都会生成随机颜色。谁能纠正我?
代码:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#para{
text-align: center;
font-size: 20px;
color: white;
}
#link{
text-align: center;
font-size: 20px;
}
</style>
<title>lab13</title>
<script type="text/javascript">
document.write('<br>'); document.write('<br>');
document.write('<p id = "para">' + 'BACKGROUND-COLOR IS RANDOMLY GENERATED' + '</p>');
function random_bg_color(){
var rgbcolor;
red = Math.floor(Math.random() * 250 + 0 );
green = Math.floor(Math.random() * 250 + 0);
blue = Math.floor(Math.random() * 250 + 0);
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
document.body.style.background = rgbColor;
document.write('<p id = "para">RGB(' + red + ', ' + green + ', ' + blue + ')</p>');
red = ("0" + red.toString(16)).substr(-2).toUpperCase();
green = ("0" + green.toString(16)).substr(-2).toUpperCase();
blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();
document.write("<p id = 'para'>HEX: #" + red + '' + green + '' + blue + '</p>');
}
random_bg_color();
function randomize() {
random_bg_color();
document.body.style.background = rgbColor;
}
</script>
</head>
<body>
<a id="a1" href="#" onclick="randomize()"> CLICK TO RANDOM </a>
</body>
</html>
输出:
【问题讨论】:
-
您在运行时生成随机颜色,其中
random_bg_color()仅被调用一次。您必须在randomize()方法中再次调用该方法以生成 new 随机颜色并设置它,即function randomize() { random_bg_color(); }
标签: javascript html css