单击链接生成随机背景颜色

时间:2017-10-12 18:53:45

标签: 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

7 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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();
};
<a id="a1" href="#" onclick="randomize()"> CLICK HERE </a>

答案 2 :(得分:1)

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

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

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

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

#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>

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

只需在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>

答案 6 :(得分:0)

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

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();
#para {
  text-align: center;
  font-size: 20px;
  color: white;
}

#link {
  text-align: center;
  font-size: 20px;
}
<a id="a1" href="#" onclick="random_bg_color()"> CLICK HERE </a>