Попытка изменить цвет фона с переменной - PullRequest
0 голосов
/ 27 сентября 2018

Попытка изменить цвет с помощью переменной, консоль работает, но цвет не меняется, когда я нажимаю на квадрат.

Цвет - это переменная, которую я хочу использовать.

Я пробовал фактическийстроковое значение и это не работает.

<!DOCTYPE html>

<html>
    <head>
        <link href="main.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <h1>Test Your Reactions!</h1>
        <p>Click on the shapes as fast as you can</p>

        <div id="shapes">

        </div>
        <script>

            function myFunction() {

                var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));

            document.getElementById("shapes").style.backgroundColour = colour;
            console.log(colour);
            }

        </script>
    </body>
</html>

Ответы [ 4 ]

0 голосов
/ 27 сентября 2018

Код ниже дает ожидаемый результат.пожалуйста, возьми.

<!DOCTYPE html>

<html>
    <head>
        <link href="main.css" rel="stylesheet" type="text/css"/>
        <style> 
            #shapes {
                width: 300px;
                height: 300px;
                background-color: coral;
                color: white;
            }
        </style>
    </head>
    <body>
        <h1>Test Your Reactions!</h1>
        <p>Click on the shapes as fast as you can</p>

        <div id="shapes" onClick="myFunction();">
            test
        </div>
        <script>

            function myFunction() {
                var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
                document.getElementById("shapes").style.backgroundColor = colour;
                console.log(colour);
            }

        </script>
    </body>
</html>
0 голосов
/ 27 сентября 2018

Вам необходимо заменить backgroundColour на backgroundColor без u:

document.getElementById("shapes").style.backgroundColour = colour;
______________________________________________________^

Должно быть:

document.getElementById("shapes").style.backgroundColor = colour;

ПРИМЕЧАНИЕ 1: Вынеобходимо вызвать функцию, чтобы увидеть эффект, и вы также должны дать своему целевому div shapes a width/height, чтобы вы могли видеть его.

ПРИМЕЧАНИЕ 2: Вы должны слушать DOMContentLoaded событие, чтобы убедиться, что все элементы загружены в DOM перед вызовом вашего скрипта.

Рабочий пример:

<!DOCTYPE html>

<html>

<head>
  <link href="main.css" rel="stylesheet" type="text/css" />
  <style>
    #shapes {
      width: 100px;
      height: 100px;
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <h1>Test Your Reactions!</h1>
  <p>Click on the shapes as fast as you can</p>
  <div id="shapes">

  </div>
  <script>
    document.addEventListener("DOMContentLoaded", function(event) {
      var shapes = document.getElementById("shapes");
      shapes.addEventListener('click', myFunction, false);
    });

    function myFunction() {
      shapes.style.backgroundColor = "#" + (Math.random() * (1 << 24) | 0).toString(16).slice(-6);
    }
  </script>
</body>

</html>
0 голосов
/ 27 сентября 2018

Попробуйте это

const shapes = document.getElementById("shapes"); // You declare once, then you can reuse

function myFunction() {
  var colour = '#'+((Math.random() *(1<<24)|0).toString(16).slice(-6));
  shapes.style.backgroundColor = colour;
  console.log(colour);
}
shapes.addEventListener('click', myFunction); // I guess you want to click somewhere
<h1>Test Your Reactions!</h1>
  <p>Click on the shapes as fast as you can</p>
<div id="shapes">Shapes</div>
0 голосов
/ 27 сентября 2018

его backgroundColor не Colour .. у вас есть дополнительный u

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...