최대 1 분 소요

Linear-gradient

  <body>
    <button>Give me color</button>
    <script src="index.js"></script>
  </body>
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 changeBtn = document.querySelector("button");
const colors = [
"#ef5777",
"#575fcf",
"#4bcffa",
"#34e7e4",
"#0be881",
"#f53b57",
"#3c40c6",
"#0fbcf9",
"#00d8d6",
"#05c46b",
"#ffc048",
"#ffdd59",
"#ff5e57",
"#d2dae2",
"#485460",
"#ffa801",
"#ffd32a",
"#ff3f34"
];
const body = document.querySelector("body");
function handleBackColor() {
const newColors = [];
for (let i = 0; i < 2; i++) {
const randomPick = Math.floor(Math.random() * colors.length);
newColors.push(colors[randomPick]);
body.style.backgroundImage = `linear-gradient(0.25turn, ${newColors})`;
}
}
changeBtn.addEventListener("click", handleBackColor);

• Html의 body를 가져옴
• 기존 배열에서 새로 넣을 새 배열을 만든다
• 반복문을 이용해서 기존배열에서 랜덤으로 추출하는 값을 2번을 받아 새 배열에 넣어준다
• 새 배열값을 body backgroundImage에 넣는다
• Linear-gradient 이용
  • 이렇게도 표현 할 수 있다
const body = document.querySelector("body");

function handleClick() {
  const a = colors[Math.floor(Math.random() * colors.length)];
  const b = colors[Math.floor(Math.random() * colors.length)];
  if (a === b) {
    return handleClick();
  }
  document.body.style.background = `linear-gradient(to left, ${a}, ${b})`;
}
changeBtn.addEventListener("click", handleBackColor);
  • 차이점은 변수를 2개 만들어 각각 랜덤값을 구한다음, body에 넣어줌

댓글남기기