[JS] 자바스크립트 기초 프로젝트_color flipper

·2023년 11월 29일
0

JS 기초 프로젝트

목록 보기
1/2
post-thumbnail

👩‍💻color flipper

버튼을 클릭하면 랜덤으로 배경색이 바뀌는 기능

HTML

  • container: background
  • contenst안에 배경색을 나타내는 p와 클릭 버튼 button 생성
...
  <body>
    <div class="container">
      <div class="contents">
        <p>Background Color: <span class="color">mint</span></p>
        <button class="button">Click Me!</button>
      </div>
    </div>
  </body>
...

Javascript

  • querySelector 를 이용하여 특정 요소를 찾는다.
  • 랜덤으로 변경시킬 color값을 colors 에 배열 형태로 집어 넣는다.
  • handleClick : 버튼이 클릭되었을 때 실행할 동작 정의
    • randomNumber: colors 경우만큼의 랜덤 숫자
    • background.style.backgroundColor : colorscolor 로 색상 변경
    • colorText.style.color : colorscolor 로 텍스트 색상 변경
    • colorText.textContent : colorsname 으로 텍스트 변경
$(document).ready(function () {
  $(function () {
    const background = document.querySelector(".container");
    const colorText = document.querySelector(".color");
    const btn = document.querySelector("button");

    const colors = [
      { id: 1, name: "red", color: "#ff0000" },
      { id: 2, name: "orange", color: "#FFA500" },
      { id: 3, name: "yellow", color: "#ffff00" },
      { id: 4, name: "lime green", color: "#32cd32" },
      { id: 5, name: "skyblue", color: "#87CEEB" },
    ];

    const handleClick = () => {
      const randomNumber = Math.floor(Math.random() * colors.length);
      background.style.backgroundColor = colors[randomNumber].color;
      colorText.style.color = colors[randomNumber].color;
      colorText.textContent = colors[randomNumber].name;
    };

    btn.addEventListener("click", handleClick);
  });
});

구현 결과


👀관련 개념

1. querySelector

특정 name,id,class를 제한하지 않고 css선택자를 사용하여 요소를 찾는다.
- querySelector(#id) => id 값 id를 가진 요소를 찾는다.
- querySelector(.class) => class 값 class를 가진 요소를 찾는다.


2. getElementbyId

괄호 안에 id값을 집어넣어 사용한다.

  • html 코드
<button id="test-btn">바뀌기 전 text</button>
  • javascript 코드: test-btn 이라는 id 값을 가진 버튼 요소를 찾고, 해당 버튼을 click 했을 때, 텍스트를 변경하는 코드
const mode = document.getElementById("test-btn");
mode.addEventListener("click", function() {
	if (mode.innerText === "바뀌기 전 text") {
		mode.innerText = "바뀐 text!";
	} else {
        mode.innerText = "바뀌기 전 text";
	}
});

3. document.body.style.backgroundColor

body 요소의 배경색을 설정하거나 가져온다.

document.body.style.backgroundColor = 'lightblue';

4. Math.floor()

소수 부분을 버림하여 정수 부분만 남긴다.

let number = 5.78;
console.log(Math.floor(number)); // 5

5. Math.random()

0 이상 1 미만의 난수를 반환한다.

// 0부터 5까지의 랜덤 숫자를 얻기
const randomNumber = Math.floor(Math.random() * 6);
    
// 1부터 5까지의 랜덤 숫자를 얻기
const randomNumber = Math.floor(Math.random() * 5) + 1;

0개의 댓글