在我的 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>
输出:
最佳答案
问题是 randomize()
只是设置背景颜色,并没有实际生成新颜色。因此,以下 randomize()
将生成一种新颜色并将背景颜色设置为该值。
它将在页面加载时调用(最后一行),链接上的 onclick
将直接调用它。
function randomize() {
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;
red = ("0" + red.toString(16)).substr(-2).toUpperCase();
green = ("0" + green.toString(16)).substr(-2).toUpperCase();
blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();
}
randomize();
关于javascript - 通过单击链接生成随机背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46716945/