Как написать код для кнопки для генерации случайных градиентов цвета фона - PullRequest
0 голосов
/ 28 марта 2020

Я хочу добавить кнопку, которая генерирует случайные линейные градиенты на фоне. Код ниже генерирует линейные градиенты, когда я нажимаю одну или другую кнопку.

var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var gradient = document.querySelector("body");
var css=document.querySelector("h3");
var random = document.getElementById("random")

css.textContent = gradient.style.background  = "linear-gradient(to right," + color1.value + "," + color2.value +")"; 

function setBackground(){
    gradient.style.background = "linear-gradient(to right," + 
    color1.value + "," + color2.value +")";
    css.textContent = gradient.style.background + ";"

}
color1.addEventListener("input", setBackground);

color2.addEventListener("input", setBackground);


1 Ответ

0 голосов
/ 28 марта 2020

Следующий фрагмент должен делать то, что вы пытаетесь достичь. Пожалуйста, не стесняйтесь спрашивать, если есть что-то, что не ясно.

const body = document.getElementsByTagName('BODY')[0];
const button = document.getElementsByTagName('BUTTON')[0];

function changeBackground(){
  body.style.background = `linear-gradient(to right,${getRandomHEXColor()},${getRandomHEXColor()})`;
}

function getRandomHEXColor() {
  const SEED = '0123456789abcdef';
  let output = '#';
  while (output.length < 7) {
    output += SEED[Math.floor(Math.random() * SEED.length)];
  }
  return output;
}

button.addEventListener("click", changeBackground);
<html>
  <body>
    <button>CHANGE BACKGROUD</button>
  </body>
</html>
...