javascript - 通过单击链接生成随机背景颜色

标签 javascript html css

在我的 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>

输出:

enter image description here

最佳答案

问题是 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/

相关文章:

javascript - 带有 Bootstrap 的菜单和使用 css 转换的 jquery

javascript - 为什么我无法从 onclick 属性调用名为clear的函数?

javascript - ReCaptcha:发送验证码时如何自动提交表单

javascript - 无法在动态对象 jquery 上绑定(bind)事件

php - Codeigniter 购物车无法添加项目

animation - CSS3 链式动画

javascript - 如何在选项卡式平面中设置 iframe 获取其中内容的高度?

javascript - Microsoft Graph 获取基本联系方式 (Node.js)

html - HTML5 input type number 可以和十六进制数一起使用吗?

html - 表单上的空白