STUDY 📒/Javascript

[바닐라JS 챌린지] DAY 11 - Randomness

South Dev 2024. 3. 1. 02:41

✔ 오늘의 강의

바닐라JS로 크롬앱 만들기: 6.0# ~ #6.2

 

✔ 목표

give me color 클릭시 랜덤으로 배경색 변경

 

✔ 조건

  1. blueprint에 colors 배열이 선언되어 있다.
  2. 사용자가 버튼을 클릭하면 colors 배열에서 두 가지 색상이 랜덤으로 선택되어야 한다.
  3. body 태그의 style을 랜덤으로 선택된 두 가지 색상을 사용해 linear-gradient로 변경한다.

힌트

더보기
  • linear-gradient : 선형 그라데이션을 만들어주는 CSS 함수 참고
  • Math.floor() : 주어진 숫자의 소수점 이하를 내림해서 반환하는 함수. 참고
  • Math.random : 0에서 1보다 작은 범위의 난수를 반환하는 함수. 참고
  • length : 배열의 길이(요소의 개수)를 반환하는 프로퍼티 참고

 

 

✔ 과정

html

<!DOCTYPE html>
<html>
  <head>
    <title>Vanilla Challenge</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/style.css" />
  </head>

  <body>
    <button>Give me color</button>
    <script src="src/index.js"></script>
  </body>
</html>

 

css

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;
}

 

JS

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

const randomBtn = document.querySelector("button");

randomBtn.addEventListener("click", (e) => {
  const color1 = colors[Math.floor(Math.random() * colors.length)];
  const color2 = colors[Math.floor(Math.random() * colors.length)];

  document.body.style.background = `linear-gradient(0.75turn, ${color1}, ${color2})`;
});

 

✔ 결과

 

반응형