열심히 끝까지

디바이스 융합 자바(Java) day 32 - 이벤트(마우스,키보드),선택자,콜백형식,윈도우 온로드, 이벤트리스너,태그추가요소,버튼추가요소,리스트제거,리스트변경,윈도우객체,히스토리객체,유효성검.. 본문

디바이스 융합 자바(Java)기반 풀스택 개발자 양성과정(수업내용)

디바이스 융합 자바(Java) day 32 - 이벤트(마우스,키보드),선택자,콜백형식,윈도우 온로드, 이벤트리스너,태그추가요소,버튼추가요소,리스트제거,리스트변경,윈도우객체,히스토리객체,유효성검..

노유림 2022. 7. 26. 15:09

[오늘 수업]

[이벤트]
화면에 박스가 하나 있을 때 
  -> 마우스 클릭(ONCLICK)을 하면 박스가 원모양으로 바뀜
        >> 기능이 추가되어있음 == 이벤트가 추가되어있음
 
>> 이벤트 기본 구성
  - 이벤트 트리거
      : 이벤트를 발생시키는 신호(html 요소에 검)
      ex) click, dbclick, mouseover, keydown, keypress,...
  - 이벤트 핸들러
      : 실제 발생되는 이벤트 내용

>> 이벤트가 진행이 안된다?
   - 트리거를 연결을 잘 했나
   - 핸들러 내용이 올바르지 않은가?

html에서 사용하는 요소에게 이름을 부여하는 방식
  - id 속성 걸어주기
  - class 속성 걸어주기
   <위 요소는 css의 형태를 만들어주기 위한 용도>
  - name 속성 걸어주기
   <위 요소를 사용해도 스타일이 뭉개지거나 하지 않음>

>> 브라우저마다 해석이 다르기 때문에 event.keyCode가 뜨지 않을 수 도 있음
    >> 따라서 어떤 환경에서 열어달라는 요구가 가끔 나옴

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>마우스 이벤트</title>

<style type = "text/css">
	#box{
		width:100px;
		height:100px;
		cursor:pointer;
		background-color:coral;	
	}
</style>

</head>
<body>

<script type="text/javascript">
	function func1(obj){
		obj.style.backgroundColor="lightblue";
	}
	function func2(obj){
		obj.style.backgroundColor="lightgray";
	}
</script>

<div id="box" onmouseover="func1(this)" onmouseout="func2(this)"></div>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>키보드 이벤트</title>
<style type="text/css">
	input[name="test"]{
		border:3px solid black;
	}
</style>
</head>
<body>

<script type="text/javascript">
	function func(){
		// 키보드를 누르면 뜨는 값
		console.log("키보드 누름");
	}
	function func1(event){
		// 키보드에 값을 넣으면 나오는 값 콘솔에 출력
		console.log(event.keyCode);
	}
</script>

<input type="text" onkeydown="func1(event)" name="test" placeholder="console 확인">


</body>
</html>

 

>> 이벤트 등록 시 어떤 요소가 변경될 지 선택자로 선택 가능
      : selector나 Element로 고르는 것이 많다
>> 종류
 : document.getElementsByTagName(태그명)
 : document.getElementById(아이디명)
 : document.getElementsByClassName(클래스명)
 : document.querySelector(선택자) - 최초 등장하는 선택자 딱 한개만 픽
 : document.querySelectorAll(선택자) - 언급한 선택자 전부 픽

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>선택자</title>
</head>
<body>

<script type="text/javascript">
	function func(){ // 버튼 연결이 흔히 보인다. Element로 많이 쓰임. 
		document.getElementById('test').style.backgroundColor="red";
	
		// 여러개의 요소를 작업할 때 요소를 한번 받아와서 작업하는 것이 보통
		// 요소들이기 때문에 elem에 값을 담음
		var elems=document.getElementsByClassName('test2');
		for(var i = 0; i < elems.length; i++){
			elems[i].style.backgroundColor='orange';
		}
	}
</script>

<button type="button" onclick="func()">색깔 바꾸기</button>

<ul>
	<li>1</li>
	<li class="test2">2</li>
	<li id="test">3</li>
	<li class="test2">4</li>
</ul>

</body>
</html>

강사님 문제-------------------
화면에 7개의 리스트 존재
버튼을 누르면 5개의 리스트 배경색이
빨주노초파남보로 변경될 수 있게 해주면 됨

+querySelector() 활용

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>무지개코드</title>
</head>
<body>

<script type="text/javascript">
	function func(){
		
		//var elems=document.getElementsByClassName('test2');
		//for(var i = 0; i < elems.length; i++){
			//elems[i].style.backgroundColor='orange';
		//}
		var seledo=document.querySelector('.test');
		for(var i = 0; i < seledo.length; i++){
			seledo.style.backgroundColor='red';
		}
	}
	function func2(){
		var seldo=document.querySelector('.test1');
		seldo.style.backgroundColor='red';

		var seldo=document.querySelector('.test2');
		seldo.style.backgroundColor='orange';
		
		var seldo=document.querySelector('.test3');
		seldo.style.backgroundColor='yellow';
		
		var seldo=document.querySelector('.test4');
		seldo.style.backgroundColor='lightgreen';
		
		var seldo=document.querySelector('.test5');
		seldo.style.backgroundColor='blue';
		
		var seldo=document.querySelector('.test6');
		seldo.style.backgroundColor='darkblue';
		
		var seldo=document.querySelector('.test7');
		seldo.style.backgroundColor='purple';
	}
	
	var color=['red','orange','yellow','lightgreen','aqua','blue','purple'];
	var elems=document.querySelectAll('li');
	for(var i=0; i<elems.length; i++){
		elems[i].style.backgroundColor=color[i];
	}
	
</script>

<button type="button" onclick="func()">색깔 바꾸기</button>

<ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
	<li>6</li>
	<li>7</li>
</ul>

</body>
</html>

 

>> 콜백 형식이란?
   ex ) 전화를 했는데 부재중이였음. 
         그 사람이 자기 자리로 돌아왔을 때, 부재중 찍힌 것을 보고 다시 전화

   : 선택해둔 요소에 약속된 신호가 감지(트리거)되면
     약속해둔 내용(이벤트)이 수행되는 것


>> 윈도우 온로드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>윈도우 온로드</title>
</head>
<body>

<script type="text/javascript">
	console.log("1");
	console.log("2");
	console.log("3");
</script>

</body>
</html>
>> 이러면 1 2 3 이 차례로 등장

- 하지만 윈도우 온로드를 사용하면?
전체 로그가 진행 된 후 윈도우 온로드가 출현
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>윈도우 온로드</title>
</head>
<body>

<script type="text/javascript">
	console.log("1");
	
	window.onload=function(){
		console.log("2");
	}

	console.log("3");
</script>

</body>
</html>

>> 1 3 진행되고 2 나옴

>>> 즉 윈도우 온로드란?
        : 작업될 것이 다 진행된 후 진행해주세요~ 라는 의미
        : 동영상과 같은 것이 그 예시, 다른 기사 다 배치된 후 동영상 재생,
          광고도 마찬가지...

>> 이벤트 리스너
    : 윈도우 온로드보다 자주 작업되며 
      콜백형식을 통해 약속을 만드는 것이 더 흔함
    : 콜백 형식을 사용하는 이유,
         : 구조 + 기능을 다 구현해야 함 + 분할 관리 가능
    : 이벤트 리스너를 등록하는 방식을 많이 사용

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 리스너</title>
<style type="text/css">
#box {
	width: 100px;
	height: 100px;
	background-color: pink;
	cursor: pointer;
}
</style>
</head>
<body>

<div id="box"></div>

<script type="text/javascript"> // 하단배치 해줄 것
	var box=document.getElementById('box');
	/*
	box.addEventListener('click',red);
	function red(){
		this.style.backgroundColor="red";
	}
	*/
	
	// 아까와 같이 콜백형식을 통해 약속을 만드는 것이 더 흔함
	// 이벤트 리스너를 등록하는 방식을 많이 사용
	box.addEventListener('click',function red(){
		this.style.backgroundColor="red";
	})
</script>

</body>
</html>

 

>> 태그 추가 요소

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>태크 추가 요소</title>
<style type="text/css">
	.container{
		background-color:lightgray;
		padding:10px;
	}
	.container div{ 
		width:100px;
		height:100px;
		margin:10px;
		background-color:coral;
	}
</style>
</head>
<body>

<div class="container"></div>

<script type="text/javascript">
	var container=document.querySelector('.container'); // 최초 발견되는 요소 하나만 들고 옴
	container.onclick=function(){
		// function을 수행하는 주체
		this.innerHTML='<div></div>';
		// 기존에 있던 문자(글자내용)를 <div>태그로 변경해달라는 것이기 때문에 누적이 아님
		
	}	
</script>

</body>
</html>

 

----------------------
>> 버튼 추가 요소

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>버튼 추가 요소</title>
</head>
<body>

<button onclick="btn()">버튼</button>

<script type="text/javascript">
function btn(){
var btn=document.createElement('button');
btn.onclick=function(){
alert('새로 만든 버튼 클릭함!');
}
var msg=document.createTextNode('새로만든버튼');
btn.appendChild(msg);
document.body.appendChild(btn);
// append : 요소추가
// chlid : 자식 추가하듯 함(계층구조로 구성)
// <btn>버튼</btn>에<btn>과 버튼 사이에
}
</script>

</body>
</html>

 

-------------------------------
>> 리스트로 하는 제거 요소

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>리스트로 하는 추가 요소</title>

<style type="text/css">
	li{
		border:1px;
		cursor:pointer;
		margin:3px;
	}
	
</style>

</head>
<body>

<ul id="list">
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
</ul>

<script type="text/javascript">
	var list=document.querySelectorAll('#list > li');
	for(var i=0; i<list.length; i++){
		list[i].addEventListener('click', function(){
			// 리스트의 부모인 ul list야! li좀 지워줘 라고 요청해야 함 
			// 그냥 제거하면 안된다! 위 방식대로 해야 함
			this.parentNode.removeChild(this);
		})
	}
</script>

</body>
</html>

예제)
5개의 리스트가 있다.
1
2
3
4

중에서 리스트를 선잭하면?
'선택한 리스트입니다' 라고 뜨게 만들기

>> 자식노드 변경 요소

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>예제</title>

<style type="text/css">
	li{
		border:1px solid black;
		cursor:pointer;
		margin:3px;
	}
</style>

</head>
<body>

<ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
</ul>

<script type="text/javascript">
	var list=document.querySelectorAll('#list > li');
	var msg=document.createElement('선택한 리스트입니다.');
	msg.setAttribute('list');
	for(var i=0; i<list.length; i++){
		list[i].addEventListener('click', function(){
			// 리스트의 부모인 ul list야! li좀 지워줘 라고 요청해야 함 
			// 그냥 제거하면 안된다! 위 방식대로 해야 함
			this.parentNode.removeChild(this);
			this.parentNode.appendChild(msg);
		});
	}
	
	var ul=document.querySelectorAll('ul');
	var list=document.querySelectorAll('li');
	for(var i=0; i<list.length; i++){
		list[i].addEventListener('click', function(){
			
			var elem=document.createElement('li');
			var msg=document.createTextNode('선택한 리스트입니다.');
	        elem.appendChild(msg);
	        ul.replaceChild(elem,this);

		});
	}
</script>


</body>
</html>

 

--------------------------------
윈도우 객체

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Window(윈도우) 객체</title>
<style type="text/css">
	button:hover{
		cursor:pointer;
	}
</style>
</head>
<body>

<button>새 창 열기</button>
<button>새 창 닫기</button>

<script type="text/javascript">
	var btn=document.querySelectorAll('button');
	var win;
	// 스코프 문제로 위에서 올려주어야 함
	btn[0].addEventListener('click', function(){
		win=window.open('https://www.naver.com','_blank');
		// 어떤 사이트를, 어떻게 열것인가?(내 창 : _self/ 새창 : _blank)
	});
	
	btn[1].addEventListener('click',function(){
		// window.open()을 닫는 것
		win.close();
	});
</script>

</body>
</html>

>> 닫을 때, win.close()가 아닌
    window.close()를 하면 열어버린 새 창이 아닌 새 창 열기, 닫기가 있는
    그 창을 닫으니 기억해 둘 것!

------------------
히스토리 객체
이동한 것을 보여주는 것

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>history 객체</title>
</head>
<body>

<a href="NewFile15.html">앞으로 가기</a>
<input type="button" value="앞으로 가기">
<script type="text/javascript">
	var btn=document.querySelector('input');
	btn.onclick=function(){
		history.forward();
	}
	
</script>
</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>history 객체</title>
</head>
<body>

<input type="button" value="뒤로 가기">
<script type="text/javascript">
	var btn=document.querySelector('input');
	btn.onclick=function(){
		history.back();
		//history.go(-1);
	}
	
</script>
</body>
</html>

 

-----------------------

>> 유효성검사

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form name="regForm" action = "NewFile17.html" method="post">
	아이디 : <input type="text" name="userId" placeholder="5글자 이상">
	<br>
	비밀번호 : <input type="password" name="userPW" placeholder="7글자 이상">
	<hr>
	<input type="submit" value="회원가입">
</form>

<script type="text/javascript">
	var form=document.forms['regForm'];
	form.onsubmit=function(){
		if(this.userId.value.length<5){
			alert('아이디는 5글자 이상이어야합니다!');
			this.userId.focus();
			return false;
		}
		if(this.userPW.value.length<7){
			alert('비밀번호는 7글자 이상이어야합니다!');
			this.userPW.focus();
			return false;
		}
	}
	
</script>

</body>
</html>