Code/프로젝트
Build 15 JavaScript Projects (바닐라 JS 코스) 1. 랜덤 색상
홀로수키
2022. 5. 27. 14:23
유튜브 채널 freeCodeCamp.org (코딩알려주는 곳 중에 제일 유명한 곳일듯)
이 채널에 올라온 영상 중에 하나를 골랐다.
바닐라 자바스크립트 프로젝트 15개 따라서 만들어보기!
그 중 첫 번째 프로젝트!
CLICK ME 버튼을 클릭하면 백그라운드 컬러가 랜덤으로 바뀌고,
background color: 옆의 텍스트도 컬러값으로 바뀐다!
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
//#f15025
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
btn.addEventListener('click', function() {
let hexColor = '#';
for(let i = 0; i < 6; i++) {
hexColor += hex[getRandomNumber()];
}
color.textContent = hexColor;
document.body.style.backgroundColor = hexColor;
})
function getRandomNumber() {
return Math.floor(Math.random() * hex.length)
}
Math.floor() 함수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다.
Math.random() 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며...(이게 뭔 소리야) -> 그냥 랜덤 숫자 반환한다고 보면 됨