JAVASCRIPT/토이 프로젝트
[JAVASCRIPT] 01_Color Flipper
예글
2022. 12. 13. 09:50
1. 목적
- 랜덤으로 배경색 바꾸기
- DOM 학습
2. 사용된 주요 개념
- arrays
- document.getElementById()
- document.querySelector()
- addEventListener()
- document.body.style.backgroundColor
- Math.floor()
- Math.random()
- array.length
innerHTML | innerText | textContent |
- Element의 속성 - 해당 Element의 HTML, XML 읽어오거나, 설정 - div 안에 있는 HTML 전체 내용 가져옴 - display:none으로 숨겨진 텍스트도 보여줌 |
- Element의 속성 - 해당 Element 내에서 사용자에게 보여지는 텍스트 값 읽어옴 - 공백 무시, 숨겨진 텍스트 보여지지 않음 |
- Node의 속성 - <script>나 <style> 태그와 상관없이 해상 노드가 가지고 있는 텍스트 값 그대로 읽음 |
1.
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
//셀렉터들 가져와서 변수에 넣기
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
//이벤트 넣기
btn.addEventListener("click", function () {
// get random number between 0 - 3 colors[3]
const randomNumber = getRandomNumber();
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber];
});
//랜덤숫자 만드는 함수
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
2.
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()]; // 색상이 #제외 5글자이므로
}
color.textContent = hexColor;
document.body.style.backgroundColor = hexColor;
});
function getRandomNumber() {
return Math.floor(Math.random() * hex.length);
}