Requirements:

  1. blueprint에 colors배열이 선언되어 있습니다.
  2. 사용자가 버튼을 클릭하면 colors배열에서 두 가지 색상이 랜덤으로 선택되어야 합니다.
  3. body태그의 style을 랜덤으로 선택된 두 가지 색상을 사용해 linear-gradient로 변경하세요.
<!DOCTYPE html>
<html>
  <head>
    <title>Vanilla Challenge</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/style.css" />
  </head>

  <body>
    <button id="js-botton">Give me color</button>
    <script src="src/index.js"></script>
  </body>
</html>
body {
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

button {
  font-size: 20px;
}

때려넣은 버전

const colors = [
  "#ef5777",
  "#575fcf",
  "#4bcffa",
  "#34e7e4",
  "#0be881",
  "#f53b57",
  "#3c40c6",
  "#0fbcf9",
  "#00d8d6",
  "#05c46b",
  "#ffc048",
  "#ffdd59",
  "#ff5e57",
  "#d2dae2",
  "#485460",
  "#ffa801",
  "#ffd32a",
  "#ff3f34"
];

const middleButton = document.querySelector("#js-botton");

function updateColor() {
  const firstNum = Math.floor(Math.random() * 17);
  const secondNum = Math.floor(Math.random() * 17);

  drawGradientBackColor(firstNum, secondNum);
}

function drawGradientBackColor(firstNum, secondNum) {
  const firstColor = colors[firstNum];
  const secondColor = colors[secondNum];

  document.body.style.background = `linear-gradient(${firstColor}, ${secondColor})`;
}

updateColor();
middleButton.addEventListener("click", updateColor);

 

정리한버전

const colors = [
  "#ef5777",
  "#575fcf",
  "#4bcffa",
  "#34e7e4",
  "#0be881",
  "#f53b57",
  "#3c40c6",
  "#0fbcf9",
  "#00d8d6",
  "#05c46b",
  "#ffc048",
  "#ffdd59",
  "#ff5e57",
  "#d2dae2",
  "#485460",
  "#ffa801",
  "#ffd32a",
  "#ff3f34"
];

const middleButton = document.querySelector("#js-botton");

function getRandomeColor(){
  return colors[Math.floor(Math.random() * 17)]
}

function handleClick(){
  const first = getRandomeColor()
  const second = getRandomeColor()
  document.body.style.background = `linear-gradient(${first}, ${second})`;
}

handleClick();
middleButton.addEventListener("click", handleClick);
[노마드코더] 바닐라JS 챌린지 - 랜덤 그라데이션 백그라운드