【问题标题】:Generate random background color by clicking on link通过单击链接生成随机背景颜色
【发布时间】: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


【解决方案1】:

问题在于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();

【讨论】:

  • 您甚至不需要在randomize() 中再次设置背景颜色,这已在random_bg_color() 中处理;)
  • 另请注意,RGB 颜色是 0-255,而不仅仅是 0-250(尽管这可能是您想要的功能)
【解决方案2】:

正如其他人所说,您必须在每次点击时生成一个新的随机值,但代码可能比所有其他答案都简单得多。

此外,您似乎正在学习 JavaScript(也许还有 HTML),所以我们不要从一开始就养成坏习惯:

  • 不要使用内联 HTML 事件属性(onclickonmouseover、 等等。)。这是大约 20 年前使用的技术 在我们拥有标准和更强大的做事方式之前。 不幸的是,它已经变得如此无处不在并且被如此广泛地使用, 大多数人(包括书籍作者)在他们使用它时仍然使用它 不应该。有很多理由不使用它们,我写过 关于那个here
  • 不要使用document.write(),除非您正在动态创建一个 新窗口,需要将内容写入其中。而是准备 HTML 元素提前用作输出容器或创建 新元素并使用现代将它们注入网页 标准(即document.createElement()element.appendChild())。
  • 不要仅仅因为您需要某人的东西而使用超链接 点击。超链接专门用于导航,所以不要 除非您实际上是在某个地方导航,否则请使用它们。大概 每个 HTML 元素都支持 click 事件,所以使用更温和的 自定义点击操作的元素。
  • 在您的 &lt;script&gt;&lt;style&gt; 元素已经有几个不需要了 现在几年。这些类型值是这些元素的默认值。

好的,考虑到所有这些,看看你的任务使用现代代码是多么简单:

#a1 { cursor:pointer; } /* Make div feel like a hyperlink */
<!DOCTYPE html>
<html>
<head>
    <title>lab13</title>
</head>
<body>

    <p id="para">BACKGROUND-COLOR IS RANDOMLY GENERATED</p>
    <!-- Use generic elements for custom click actions, not <a> elements: -->
    <div id="a1">CLICK TO RANDOM</div>
    <div id="output"></div>
    
    <!-- By placing the script at the end of the HTML, you can be sure
         that scanning for HTML elements will work.     -->
    <script>
      var link = document.getElementById("a1");
      var output = document.getElementById("output");
      // And when the link is clicked:
      link.addEventListener("click", getRandom);          
      
      function getRandom(){
        // 16777215 (decimal) == ffffff in hexidecimal
        var newColor = '#'+Math.floor(Math.random()*16777215).toString(16);
        
        // Convert hex to RGB:
        var rgbColor = newColor.replace('#','');
        var r = parseInt(rgbColor.substring(0,2), 16);
        var g = parseInt(rgbColor.substring(2,4), 16);
        var b = parseInt(rgbColor.substring(4,6), 16);
        var result = 'rgba(' + r + ',' + g + ',' + b + ')';
        
        document.body.style.backgroundColor = newColor;
        output.textContent = newColor + " - " + result;
      };
      
      // We want the background to get a random color as soon as the page loads
      // as well as when the link is clicked, so the function will be called right away      
      getRandom();  
    </script>
</body>
</html>

【讨论】:

  • 我还需要在屏幕上显示 hexaCode 和 RGB 颜色值如预期输出所示。我需要为此创建元素吗?
  • 你可以。但是,您可以将 RGB 值连接到 HEX 值旁边。
  • @Scott 要求为 CLICK TO RANDOM 创建链接
  • @Scott 我想显示颜色值和十六进制值。我应该创建 P 元素吗?
  • @pari 好吧,您可以将链接放回原来的位置,但这是错误的,您应该让要求您这样做的人这样做,就像为此目的使用超链接一样在语义上不正确,可能会对依赖屏幕阅读器软件的用户产生不利影响。
【解决方案3】:

只需要将函数调用放在正确的位置即可!

function randomize() {
  random_bg_color();
  document.body.style.background = rgbColor;
}

【讨论】:

    【解决方案4】:

    您应该在 randomize 函数中调用 random_bg_color(); 以便每次都重新生成新颜色。

    【讨论】:

      【解决方案5】:

      function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      };
      
      function randomize() {
        document.body.style.background = getRandomColor();
      };
      &lt;a id="a1" href="#" onclick="randomize()"&gt; CLICK HERE &lt;/a&gt;

      【讨论】:

        【解决方案6】:

        只需在 onclick 中调用 random_bg_color()。

        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;
        
        
                red = ("0" + red.toString(16)).substr(-2).toUpperCase();
                green = ("0" + green.toString(16)).substr(-2).toUpperCase();
                blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();
        
        
                }
        
                random_bg_color();
        <!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>
        </head>
        <body>
        
            <a id="a1" href="#" onclick="random_bg_color()"> CLICK HERE </a>
        
        </body>
        </html>

        【讨论】:

        • 我更新了代码...见上面我的预期输出。每次我点击链接时,它也会生成随机颜色和文本。
        • 当我第一次点击链接时,它会生成随机颜色并且链接消失了。我该怎么办?
        【解决方案7】:

        问题是你调用了不正确的函数。

        OnClick 需要调用函数:random_bg_color

        我修复了你的 sn-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;
        
        
          red = ("0" + red.toString(16)).substr(-2).toUpperCase();
          green = ("0" + green.toString(16)).substr(-2).toUpperCase();
          blue = ("0" + blue.toString(16)).substr(-2).toUpperCase();
        
        
        }
        
        random_bg_color();
        #para {
          text-align: center;
          font-size: 20px;
          color: white;
        }
        
        #link {
          text-align: center;
          font-size: 20px;
        }
        &lt;a id="a1" href="#" onclick="random_bg_color()"&gt; CLICK HERE &lt;/a&gt;

        【讨论】:

        • 我更新了代码...见上面我的预期输出。每次我点击链接时,它也会生成随机颜色和文本。
        • 当我第一次点击链接时,它会生成随机颜色并且链接消失了。我该怎么办?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 2018-09-19
        相关资源
        最近更新 更多