使用javascript随机改变颜色

时间:2021-05-29 22:13:22

标签: javascript

<!DOCTYPE html>
<html>
    <head>
        <title>Button Homework</title>
        
        <script>
        
            function first()    {
                document.getElementById('type1').style.position = 'absolute';
                document.getElementById('type1').style.left= "100px";
                document.getElementById('type1').style.top= "200px";
                var red = Math.floor(Math.random() * 256);
                var green = Math.floor(Math.random() * 256);
                var blue = Math.floor(Math.random() * 256);

                var newColor = "rgb("+ red + "," + green + "," + blue +")";
            }
            
            function second()   {
                document.getElementById('type1').style.position = 'absolute';
                document.getElementById('type1').style.left= "0px";
                document.getElementById('type1').style.top= "80px";
            }
        </script>
    </head>
    <body>
        <h1>Special Button</h1>
        
        <input id = 'type1' type = 'button' value = 'Click' onclick = 'output();'
                            onmouseover= 'first()' onmouseout= 'second()';' />
    </body>
</html>

每次将鼠标悬停在按钮上时,我都试图让按钮更改为随机颜色,但我似乎无法让它工作,如果有人知道怎么做,请帮助我。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要做的就是将颜色分配给样式属性。在本例中为按钮的背景颜色。

function first() {
  var red = Math.floor(Math.random() * 256);
  var green = Math.floor(Math.random() * 256);
  var blue = Math.floor(Math.random() * 256);

  var newColor = "rgb(" + red + "," + green + "," + blue + ")";
  document.getElementById("type1").style.backgroundColor = newColor;
}

答案 1 :(得分:0)

如果您希望作业看起来像是从互联网上复制的:

<!DOCTYPE html>
  <head>
    <title>Button Homework</title>
    <style>
      #type1{
        position: absolute;}

      #type1.mouseover{
        left: 100px;
        top: 200px;}

      #type1:not(.mouseover){
        left: 0px;
        top: 80px;}
    </style>
  </head>
  <body>
    <h1>Special Button</h1>
    <input id="type1" onclick="Output()" onmouseover="MouseOver(this)" onmouseout="MouseOut(this)" type="button" value="click">
    <script>
      function MouseOver(button) {
         button.classList.add('mouseover');
         //set backgroundColor to random hex string
         button.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
       }

       function MouseOut(button) {
         button.classList.remove('mouseover');
       }

       function Output() {
         //whatever this does
       }
    </script>
  </body>
</html>

请注意,移动按钮位置会触发 mouseout 事件,因此会变得非常疯狂。当您将 <style> 内嵌在代码段中时,它似乎不适用。