[대구AI스쿨] 자율개발일지 자바스크립트 1-2강 변수와 데이터타입

김선아·2021년 10월 15일
0

대구AI스쿨 개발일지

목록 보기
44/46

변수와 데이터 타입 1-2강

클릭 버튼을 누르면 랜덤으로 색상이 변하는 상자 만들기

html에서 상자를 공간과 버튼을 만들어 준다.

<div id="color-bg">
    <button id="btn" type="button">클릭</button>
</div>

css↓

#color-bg {
	width: 500px;
	height: 500px;
	background: black;
}

#btn {
	width: 100px;
	height: 50px;
	line-height: 50px;
	
	background: purple;
	color: #fff;
	
	font-size: 20px;
}

java script↓

// yellow, green, pink, #dc143c, rgba(123, 123, 123, 0.5)

var colors = [
	'yellow',
	'green',
	'pink',
	'#dc143c',
	'rgba(123, 123, 123, 0.5)'
];

var bg = document.getElementById('color-bg');
var btn = document.getElementById('btn');

// document라는 객체는 html에 영향력을 발휘하는 객체이다.
// 자바스크립트 세가지 종류 중 '클라이언트 측 자바스크립트'에 해당한다.
// html 제어하고, 브라우저를 제어


// btn.addEventListener()
// 콜백 함수 : 호출 기호 없이 특정 조건 하에 호출되는 함수
btn.addEventListener('click', function() {
	
	//console.log('Hello')
	
	// 0 ~ 4
	var random = Math.floor(Math.random() * 5);
	//console.log(random);
	//console.log(colors[random]);
	
	
	// CSS : background-color, border-radius, margin-top 
	// 자바스크립트에서는 캐멀케이스로 작성해야한다.
	bg.style.backgroundColor = colors[random];

})

// 위에서 선언한 bg, btn이 객체가 됨.
// 이름없는 함수 function()은 익명함수라고 한다.
// 함수를 호출하지 않았는데도, 클릭하면 Hello가 출력된 
// addEventListenr라는 메서드에서 두번째 수를 자동 호출(console.log)이 자동실행 되도록 미리 설정되어있기 때문이다. 콜백함수라고 한다.



// 1~6 숫자를 가져오는 게임
// Math.random()                     : 0 < 1 (0 ~ 0.99999~)
// Math.random() * 6                 : 0 < 6 (0 ~ 5.99999~)
// Math.floor(Math.random() * 6)     : 0 ~ 5
// Math.floor(Math.random() * 6) + 1 : 1 ~ 6

console.log(Math.random());
console.log(Math.random() * 6);
console.log(Math.floor(Math.random()*6));
console.log(Math.floor(Math.random()*6)+1);

코드펜에서 작성

0개의 댓글