1

Написал все что мне нужно, только что то не могу вдуплить, как мне описать инструкцию что-бы рандомный колор менялся каждые 20 пикселей на новый. Ну и еще добавлю, что только на чистом js. Спасибо!

<!DOCTYPE html>
<html>
    <head>
        <title>Kwadrat - JS</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div id="but" style="position: absolute;width: 50px;height: 50px;"></div>

    <script type="text/javascript">
        var but = document.getElementById("but");
        var direction;
        var currentValue = 0;
        var width = screen.width;
        var maxwidth = width - 100;
        var position = maxwidth /2;

        but.style.background = "#" + Math.random().toString(16).slice(2, 8);

        function run(){
            if(currentValue === maxwidth) direction = -5;
            if(currentValue === 0) direction = 5;
            if (currentValue >= position) {
            but.style.width = "100px";
            but.style.height = "100px";
        } else {
            but.style.width = "50px";
            but.style.height = "50px";
        }

            currentValue += direction;
            but.style.left = currentValue + "px";

        }
        window.onload = function(){
            var interval = setInterval(run,50);
        };
    </script>
</body>
</html>

0

1 ответ 1

2

Вот так, например:

if (currentValue % 20 === 0){
    but.style.background = "#" + Math.random().toString(16).slice(2, 8);
}

var but = document.getElementById("but");
        var direction;
        var currentValue = 0;
        var width = screen.width;
        var maxwidth = width - 100;
        var position = maxwidth /2;

        but.style.background = "#" + Math.random().toString(16).slice(2, 8);

        function run(){
            if(currentValue === maxwidth) direction = -5;
            if(currentValue === 0) direction = 5;
            if (currentValue >= position) {
            but.style.width = "100px";
            but.style.height = "100px";
        } else {
            but.style.width = "50px";
            but.style.height = "50px";
        }

            currentValue += direction;
            but.style.left = currentValue + "px";
            if(currentValue%20 === 0){
              but.style.background = "#" + Math.random().toString(16).slice(2, 8);
            }
        }
        window.onload = function(){
            var interval = setInterval(run,50);
        };
<div id="but" style="position: absolute;width: 50px;height: 50px;"></div>

Правда Ваш способ получения цвета не идеален

Math.random().toString(16)

не обязательно будет нужной длины, например

console.log((0.5).toString(16))

Можно сделать так:

var color = '#';
while (color.length < 7) 
   color += Math.random().toString(16).substring(2);
color = color.substring(0, 7);
console.log(color);

5
  • моему браузеру твой скрипт не понравился 18 мар 2019 в 21:41
  • @nosferatu-id что сказал? 18 мар 2019 в 21:42
  • странно вышло, после выполнения твоего кода хром меня выкинул 18 мар 2019 в 21:44
  • "if (currentValue % 20 === 0){ but.style.background = "#" + Math.random().toString(16).slice(2, 8); }" Спасибо! Работает как надо, об этом я и просил.
    – Vadim
    18 мар 2019 в 21:54
  • 1
    @Vadim я в ответе написал про опасность Math.random().toString(16) учтите это 18 мар 2019 в 21:56

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.