<실습예제1> 버튼 클릭시 이미지를 좌,우로 움직이게 하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example.html</title>
<style>
#catImg{
/* 왼쪽 마진이 변경될 때 1초동안 변경되도록 하고 끝지점에서는 부드럽게 마무리 */
/* transition: margin-left 1s ease-out;*/
transition-property: margin-left;
transition-duration: 1s;
transition-timing-function: ease-out;
}
</style>
</head>
<body>
<button id="moveRight">우측으로 움직이기</button>
<button id="moveLeft">좌측으로 움직이기</button>
<br>
<img src="images/cat.png" id="catImg">
<script>
//페이지 로딩 시점에 num이라는 변수를 만들고 초기값 0을 대입하기.
let num=0;
document.querySelector("#moveRight").addEventListener("click", function(){
//함수 안에서 함수 바깥쪽에 정의된 변수를 참조할수있다.
//num = num+100;
num += 100;
document.querySelector("#catImg").style.marginLeft=num+"px";
});
document.querySelector("#moveLeft").addEventListener("click", function(){
//num = num-100;
num -= 100;
document.querySelector("#catImg").style.marginLeft=num+"px";
});
</script>
</body>
</html>
- 이미지를 오른쪽으로 움직이기 → 왼쪽에 마진 주기
누를때마다 100px씩 오른쪽으로 움직이게 하려면 마진+변수와 대입연산자를 활용
- 숫자와 문자를 더하면 100+"px" = 100px 이라고 나온다.
- global 영역은 페이지를 로딩할때 실행되고,
document.~ 안쪽은 local 영역으로 클릭할 때마다 실행되는 영역
- 변수를 locla 영역에 넣으면, 버튼을 누를 때마다 num이라는 변수가 새롭게 만들어진다.
- document.~ 안에 변수를 넣으면 매번 num=0;이 되어 num=num+100; 코드가 100이상으로 올라가지 않는다.
→ 변수(num) 선언을 global 영역으로 옮겨주면 된다.
(함수 안에서는 함수 바깥쪽에 정의된 변수를 참조할 수 있다.)
- moveLeft 버튼도 동일하게 만들어 num=num-100; 을 대입
num = num+100; == num += 100;
num = num-100; == num -= 100;
- += -= 비교연산자 숙지하기!!
[ style 적용 ]
<style>
#catImg{
transition-property: margin-left;
transition-duration: 1s;
transition-timing-function: ease-out;
}
</style>
- javascript로는 한번에 이동하지만, css는 transition을 사용해 움직이는 과정을 천천히 보여줄 수 있다.
- transition: margin-left 1s ease-out; 과 같이 한 줄로 쓸 수도 있다.
[ 참고 ]
- 를 쓰면 산술연산자로 인지되므로, css의 속성명을 js로 옮길때는 camel case로 쓴다.
ex) style : margin-left, background-color, border-top-width → js : marginLeft, backgroundColor, borderTopWidth
- style: margin-left:100px;
- js: document.querySelector("#catImg").style.marginLeft="100px";
<실습예제2> : loop반복문 사용해서 문자열이 한번에 바뀌게 해보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example2.html</title>
</head>
<body>
<h1>반복문 사용 연습</h1>
<button id="changeBtn">바꾸기</button>
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div>div6</div>
<div>div7</div>
<div>div8</div>
<div>div9</div>
<div>div10</div>
<script>
//바꾸기 버튼을 눌렀을 때 모든 div의 innerText가 "고양이"로 변경되도록 프로그래밍 해보세요.
document.querySelector("#changeBtn").addEventListener("click",function(){
//모든 div의 참조값을 배열에 담아오기
const divs=document.querySelectorAll("div");
//반복문 돌면서 모든 div의 innerText변경하기
for(let i=0; i<divs.length; i++){
divs[i].innerText="고양이";
}
});
</script>
</body>
</html>
- 버튼을 눌렀을때 일어나야하므로, 먼저 .eventListener를 만들고 그 영역 안에서 코딩하기
- div 참조값 배열(divs)을 가져와서 for 문을 사용해 반복 실행
const divs=document.querySelectorAll("div");
- 모든 div의 참조값을 배열로 만들어 변수로 넣기
querySelector : 문서객체의 쿼리값을 가져온다.
querySelectorAll :모든 문서객체의 쿼리값을 배열에 담아서 리턴한다.
<실습예제3>: 문자열이 버튼 누를때마다 순차적으로 하나씩 바뀌게 해보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example3.html</title>
</head>
<body>
<button id="changeBtn">하나씩 바꾸기</button>
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div>div6</div>
<div>div7</div>
<div>div8</div>
<div>div9</div>
<div>div10</div>
<script>
/* 1. 바꾸기 버튼을 누르면 위에서 부터 순서대로 한번에 하나씩만 div 의 innerText 가 "김구라" 로
변경되도록 해 보세요.
2. div10 까지 모두 바뀐후에 버튼을 또 누르면 "더 이상 바꿀수 없습니다." 라는 알림을 띄워 보세요
*/
//배열의 인덱스로 사용할 변수를 만들고 초기값 0 대입
let index=0;
document.querySelector("#changeBtn").addEventListener("click", function(){
let divs=document.querySelectorAll("div");
//만일 현재 index 가 10(배열의 size) 과 같다면
//알림을 띄우고 아래의 코드를 실행하지 않기(함수를 여기서 종료시키기)
if(index == divs.length){
alert("더 이상 바꿀수 없습니다.");
return;
}
//index 변수에 있는 값을 이용해서 배열의 특정방 참조해서 innerText 수정하기
divs[index].innerText="고양이";
//index 1 증가 시키기
index++;
});
</script>
</body>
</html>
- 변수선언 영역 중요!!
const divs=document.querySelectorAll("div");
→ 모든 div의 참조값이 배열[] 로 담긴다.
divs[0].innerText="고양이";
divs[1].innerText="고양이";
divs[2].innerText="고양이";
↓
let index=0; 을 추가한 후
divs[index].innerText="고양이" 로 수정할 수 있다.
- let index=0; 은 페이지 로딩시점(global 영역)에 만드는 것으로 바꿔야 한다!
if(num<divs.length)
if(index==10)
- 위 예제에서는 동일한 코드로 사용할 수 있다.
<실습예제4> : 비교연산자, 논리연산자 사용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example4.html</title>
</head>
<body>
<h1>논리 연산자 테스트 예제</h1>
<input type="text" id="height" placeholder="키를 입력하세요..."/>
<input type="text" id="weight" placeholder="몸무게를 입력하세요..."/>
<button id="checkBtn">놀이기구를 탈 수 있는지 확인하기</button>
<p id="result"></p>
<script>
/*
키가 너무 작거나 몸무게가 너무 크면 탈 수 없는 놀이기구가 있다.
키는 150 이상, 몸무게는 100 미만이 기준이다.
키와 몸무게를 입력하고 확인하기 버튼을 누르면
해당 놀이기구를 탈 수 있는지 없는지 메세지를
p 요소의 innerText로 출력하는 프로그래밍을 해보세요.
"탈 수 있습니다." "탈 수 없습니다."
-hint; 논리연산자 &&, 비교연산자 활용
*/
document.querySelector("#checkBtn").addEventListener("click", function(){
let h=Number(document.querySelector("#height").value) >= 150;
let w=Number(document.querySelector("#weight").value) < 100;
//만일 키가 150 이상이고 그리고 몸무게가 100 미만이라면
if(h&&w == true){
document.querySelector("#result").innerText="탈 수 있습니다.";
}else{
document.querySelector("#result").innerText="탈 수 없습니다.";
};
});
</script>
</body>
</html>
- && and 연산자 : 두가지 값이 모두 true 일때만 결과가 true가 된다.
document.querySelector("#checkBtn").addEventListener("click", function(){
let h=Number(document.querySelector("#height").value) >= 150;
let w=Number(document.querySelector("#weight").value) < 100;
if(h&&w == true){
document.querySelector("#result").innerText="탈 수 있습니다.";
}else{
document.querySelector("#result").innerText="탈 수 없습니다.";
};
});
document.querySelector("#checkBtn").addEventListener("click", function(){
let h=Number(document.querySelector("#height").value);
let w=Number(document.querySelector("#weight").value);
if(h>=150 && w<100){
document.querySelector("#result").innerText="탈 수 있습니다.";
}else{
document.querySelector("#result").innerText="탈 수 없습니다.";
};
});
- 위의 두개는 같은 의미의 코드! 변수(h,w)에 무엇을 넣었는지만 다를 뿐
<실습예제5> : 수학 관련 함수 사용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example5.html</title>
</head>
<body>
<h1>수학에 관련된 함수 사용해 보기</h1>
<script>
//sin30, tan45, cos60 등 삼각함수의 값을 얻어내기
let result1=Math.sin(30*Math.PI/180); //sin 30도
let result2=Math.tan(45*Math.PI/180); //tan 45도
//무작위의 랜덤한 숫자 얻어내기
let ranNum1=Math.random(); // 0이상 1미만의 랜덤한 실수 얻어내기
let ramNum2=Math.random(); // 0이상 10미만의 랜덤한 실수 얻어내기
//반올림, 내림, 올림
let result3=Math.round(10.5); // 반올림값 10
let result4=Math.floor(5.6); // 내림값 5
let result5=Math.floor(3.1); // 올림값 4
let ranNum3=Math.floor(Math.random()*10); // 0~9 사이의 랜덤한 정수
let ranNum4=Math.floor(Math.random()*10)+1; // 1~10 사이의 랜덤한 정수
let ranNum5=Math.floor(Math.random()*45)+1; // 1~45 사이의 랜덤한 정수
</script>
</body>
</html>
콘솔에서 제공하는 Math라는 함수(object)가 있다. sin, cos, tan 전부 사용가능.
-단, 숫자에는 그냥 ˚ 가 아니라 30*PI/180 을 곱한값(라디안)을 넣어야한다.
- Math.round : 반올림
- Math.floor : 내림
- Math.ceil : 올림
- Math.random() : 0이상 1미만의 랜덤한 실수를 얻어냄
- Math.floor(Math.random()*10) : 0~9 사이의 랜덤한 정수
- Math.floor(Math.random()*2) : 0 또는 1을 랜덤하게 내보낼 수 있음
<실습예제6> : 수학 관련 함수 사용(가위바위보)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example6.html</title>
</head>
<body>
<button id="myBtn">눌러보셈</button>
<p id="result"></p>
<select id="mySelect">
<option>선택</option>
<option>가위</option>
<option>바위</option>
<option>보</option>
</select>
<script>
/*
버튼을 눌렀을 때 아래 배열에 있는 3개의 문자열 중에 하나가 랜덤하게
p 요소의 innerText로 출력되도록 해 보세요.
*/
const data=["가위", "바위", "보"];
document.querySelector("#myBtn").addEventListener("click", function(){
let num=Math.floor(Math.random()*3);
// 가위 바위 보 중에 하나의 문자열을 innerText로 출력하기
document.querySelector("#result").innerText=data[num];
// 가위 바위 보 중에 하나의 문자열을 select의 value로 넣어주기
document.querySelector("#mySelect").value=data[num];
});
</script>
</body>
</html>
- Math.random 함수를 사용한 가위바위보 랜덤 출력
- 가위, 바위, 보 를 array에 넣고, num을 0,1,2 중 하나가 랜덤으로 나오는 변수로 지정하여 data[num] 형태로 참조하기!
<실습예제7> : 메세지 저장, 출력
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Step07_example7.html</title>
</head>
<body>
<h1>배열에 아이템 추가하고 필요한 시점에 활용하기</h1>
<input type="text" id="inputMsg">
<button id="saveBtn">배열에 저장</button>
<button id="showBtn">콘솔에 출력</button>
<p>현재 저장된 메세지 갯수: <strong id="amount">0</strong></p>
<script>
/* [dataType4 참고]
input 요소에 문자열을 입력하고 저장 버튼을 누르면
1. 입력한 문자열을 아래 배열에 저장한다.
2. 알림창에 "저장했습니다."를 띄운다.
3. id가 amount인 요소의 innerText로 몇개의 메세지가 저장되었는지 출력하도록 해 보세요.
콘솔에 출력하기 버튼을 누르면
배열에 저장된 모든 문자열을 하나씩 콘솔창에 아래와 같은 형식으로 출력해 보세요.
0 번방: 메세지1
1 번방: 메세지2
2 번방: 메세지3(실제 저장된 메세지)
*/
const msgs=[]; // 메세지를 저장할 배열
document.querySelector("#saveBtn").addEventListener("click", function(){
//입력할 문자열을 읽어와서
let msgList=document.querySelector("#inputMsg").value;
//배열에 밀어넣기(저장하기)
msgs.push(msgList);
//알림 띄우기
alert("저장했습니다.");
//저장된 메세지 갯수(배열의 길이) 출력
document.querySelector("#amount").innerText=msgs.length+"개";
document.querySelector("#inputMsg").value=""
});
document.querySelector("#showBtn").addEventListener("click", function(){
for(let i=0; i<msgs.length; i++){
console.log(i+"번방: 메세지"+msgs[i]);
};
});
</script>
</body>
</html>
- 버튼을 누르면 사용자가 입력하는 메시지가 저장되도록 함
- 해당 메시지를 모아서 콘솔 창에서 출력
- 특정시점에 일괄 실행할 javascript를 함수 안에 모아놓고, 그 시점이 되면 한번에 실행한다.
- 배열은 반복문이 따라오는경우가 많다.
(참고) 두가지를 구분하기 (number, object 대입했을 때의 차이)
let v1=document.querySelector("#inputMsg").value;
v1="hello";
빨간색: 변수 v1 안의 값을 대체하는 것. (작동하지 않음)
let input1=document.querySelector("#inputMsg");
input1.value="hello";
파란색: input1.value를 참조해서 변수 안의 값을 바꿔놓은것
'국비교육(22-23)' 카테고리의 다른 글
7일차(2)/DB_Oracle(2) : SELECT문 (0) | 2022.10.14 |
---|---|
7일차(1)/DB_Oracle(1) : 설치 및 기본정보 (0) | 2022.10.14 |
6일차(1)/javascript 기초 : 동적 요소 만들기(2) (0) | 2022.10.13 |
5일차(5)/javascript 기초 : 동적 요소 만들기 (0) | 2022.10.12 |
5일차(4)/javascript 기초 : 연산자 operator (0) | 2022.10.12 |