Study Web Development

12월 29일

이전으로

jQuery

7. 다양한 효과와 애니메이션

효과 메서드

  1. 새 HTML 파일 s05_animate.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>효과와 애니메이션</title>
<style type="text/css">
	h1 {width: 50px; height: 30px; background-color: crimson; font-size: 100%;}
	h2 {width: 50px; height: 30px; background-color: orange; font-size: 100%;}
	h3 {width: 50px; height: 30px; background-color: aqua; font-size: 100%;}
</style>
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
	$(function() {
		// animate({애니메이션 속성}, '효과 속도', 콜백 함수)
		// 애니메이션 속성 : 모션으로 적용할 속성을 스타일(CSS)을 이용해 입력
		$('h1').animate({
			marginLeft:'250px'
		}, 5000, function() { // 애니메이션 종료시 수행할 작업
			alert('도착 완료');
		});
		
		$('h2').animate({
			marginLeft:'250px',
			opacity:0.3,
			width:'100px',
			height:'100px' // <h2> 태그의 높이(=점유 공간) 변경되면 맞닿아 있는 <h3> 태그 역시 (별도의 애니메이션 속성을 주지 않더라도) 움직이게 
		}, 5000);
		
		$('h3').animate({marginLeft:'250px'}, 3000)
				.animate({marginLeft:'100px'}, 2000); // animate() 메서드의 경우 효과 속도와 콜백 함수를 인자로 받아야 하기 때문에 같은 메서드를 여러 번 사용할 때 (css() 메서드처럼 객체표기법 대신에) .으로 연결
	});
</script>
</head>
<body>
	<h1>내용</h1>
	<h2>내용</h2>
	<h3>내용</h3>
</body>
</html>

jQuery UI

Download

https://jqueryui.com/download/

  1. Version 1.13.0(Stable, for jQuery1.8+)을 다운로드
  2. 압축 해제 후 jquery-ui.jsjquery-ui.min.js 파일을 C:\javaWork\workspace_jsp\javaScript\src\main\webapp\js로 이동
  3. 압축 해제된 폴더에서 .css 파일들과 images 폴더를 C:\javaWork\workspace_jsp\javaScript\src\main\webapp\css로 이동

Demos

https://jqueryui.com/demos/

draggable/droppable
  1. 새 폴더 ch18-jQueryUI를 생성하고 새 HTML 파일 s01_draggable.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Draggable</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<style type="text/css">
	#draggable {width: 150px; height: 150px; padding: 0.5em;}
</style>
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		$('#draggable').draggable(); // jQueryUI의 메서드를 이용하면 HTML5 표준보다 간편하게 드래그 기능을 구현 가능
	});
</script>
</head>
<body>
	<div id="draggable" class="ui-widget-content"> <!-- jQueryUI의 내장 클래스 부여 -->
		<p>Drag me around</p>
	</div>
</body>
</html>
  1. 새 HTML 파일 s02_droppable.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Droppable</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<style type="text/css">
	#draggable {width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0;}
	#droppable {width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px;}
</style>
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		$('#draggable').draggable();
		$('#droppable').droppable({ // 옵션 값을 객체로 전달
			drop:function() { // draggable한 요소가 영역에 진입하고 놓여졌을 때 발생하는 이벤트
				$(this).addClass('ui-state-highlight') // 이벤트가 발생한 <div> 태그에 jQueryUI의 내장 클래스 부여
						.find('p') // 이벤트가 발생한 <div> 태그 하위의 <p> 태그에 접근
						.html('Dropped!'); // <p> 태그의 내용을 변경
			},
			out:function() { // draggable한 요소가 영역을 벗어났을 때 발생하는 이벤트
				$(this).removeClass('ui-state-highlight')
						.find('p')
						.html('Drop here'); // <p> 태그의 내용을 원래대로 되돌림
			},
			over:function() { // draggable한 요소를 영역에 드래그 오버할 때 발생하는 이벤트
				$(this).find('p').html('Dragged over');
			}
		});
	});
</script>
</head>
<body>
	<div id="draggable" class="ui-widget-content"> <!-- jQueryUI의 내장 클래스 부여 -->
		<p>Drag me around</p>
	</div>
	<div id="droppable" class="ui-widget-header"> <!-- jQueryUI의 내장 클래스 부여 -->
		<p>Drop here</p>
	</div>
</body>
</html>
datepicker
  1. 새 HTML 파일 s03_datepicker.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>datepicker</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		// $('#datepicker').datepicker();
		$('#datepicker').datepicker({ // 옵션 값을 객체로 전달
			showMonthAfterYear:true, // 달력에서 월 연도 순이 아닌 연도 월 순으로 표시
			dateFormat:'yy-mm-dd', // 선택한 날짜를 YYYY-MM-DD 형식으로 반환; YY-MM-DD 형식으로 반환하려면 값을 y-mm-dd으로 지정
			dayNamesMin:['', '', '', '', '', '', ''], // 달력에서 요일을 영문이 아닌 한글로 표시
			monthNames:['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'] // 달력에서 월을 영문이 아닌 한글로 표시
		});
	});
</script>
</head>
<body>
	<p>
		Date : <input type="text" id="datepicker">
	</p>
</body>
</html>
  1. 새 HTML 파일 s04_datepicker.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>datepicker</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript" src="../js/datepicker-ko.js"></script> <!-- datepicker를 한국어로 사용; jQueryUI 메인 스크립트보다 나중에 로딩되어야 함 -->
<script type="text/javascript">
	$(function() {
		// $.datepicker.setDefaults($.datepicker.regional['']); // restore the default localizations
		$('#datepicker').datepicker({
			showMonthAfterYear:true,
			changeYear:true, // 달력에서 연도를 드롭다운 리스트에서 선택하여 변경 가능
			changeMonth:true, // 달력에서 월을 드롭다운 리스트에서 선택하여 변경 가능
			// dayNamesMin:['일', '월', '화', '수', '목', '금', '토'],
			// monthNamesShort:['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'] // 월이 드롭다운 리스트로 렌더링될 때는 monthNames가 아닌 monthNamesShort를 사용함
		});
	});
</script>
</head>
<body>
	<p>
		Date : <input type="text" id="datepicker">
	</p>
</body>
</html>
dialog
  1. 새 HTML 파일 s05_dialog.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dialog</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		$('#dialog').dialog(); // 선택된 태그를 다이얼로그 창으로 변경
	});
</script>
</head>
<body>
	<!-- 다이얼로그 창 -->
	<div id="dialog" title="Basic dialog">
		<p>This is the default dialog. 
			This is the default dialog. 
			This is the default dialog. 
			This is the default dialog.</p>
	</div>
	
	<div>Welcome</div>
</body>
</html>
  1. 새 HTML 파일 s06_dialog.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dialog</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		$('#dialog').dialog({ // 옵션 값을 객체로 전달
			autoOpen:false, // 다이얼로그 창이 기본적으로 열려 있지 않도록 변경
			show:{ // 다이얼로그 창이 open될 때의 효과 설정
				effect:'blind',
				duration:1000
			},
			hide:{ // 다이얼로그 창이 close될 때의 효과 설정
				effect:'explode',
				duration:1000
			}
		});
		
		// 이벤트 연결
		$('#opener').on('click', function() {
			$('#dialog').dialog('open'); // 다이얼로그 창 열기
		});
		$('#closer').on('click', function() {
			$('#dialog').dialog('close'); // 다이얼로그 창 닫기
		});
	});
</script>
</head>
<body>
	<!-- 다이얼로그 창 -->
	<div id="dialog" title="Basic dialog">
		<p>This is the default dialog. 
			This is the default dialog. 
			This is the default dialog. 
			This is the default dialog.</p>
	</div>
	
	<button id="opener">Open dialog</button>
	<button id="closer">Close dialog</button>
</body>
</html>
  1. 새 HTML 파일 s07_dialog.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dialog</title>
<link rel="stylesheet" href="../css/jquery-ui.min.css">
<script type="text/javascript" src="../js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript">
	$(function() {
		$('#dialog').dialog({
			modal:true, // 다이얼로그 창이 열려 있으면 페이지 내 다른 요소들은 비활성화됨(클릭, 드래그 등 상호작용 불가)
			resizable:false, // 다이얼로그 창의 크기 변경을 불가능하게 변경; 기본값은 true
			buttons:{ // 다이얼로그 창 내에 버튼을 추가
				'Delete all items':function() { // key는 버튼의 문구로 표시되며 함수는 버튼을 눌렀을 때 실행됨
					$(this).find('p').css('display', 'none');
				},
				Cancel:function() {
					$(this).find('p').css('display', '');
				}
			}
		});
	});
</script>
</head>
<body>
	<!-- 다이얼로그 창 -->
	<div id="dialog" title="Basic dialog">
		<p>This is the default dialog. 
			This is the default dialog. 
			This is the default dialog. 
			This is the default dialog.</p>
	</div>
	
	<div>Hello World!!</div>
</body>
</html>

HTML5

7. Web Storage API

7-2 로컬 스토리지

  1. 프로젝트 HTML에 새 폴더 ch17-webStorage 생성하고 새 HTML 파일 s01_localStorage.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로컬 스토리지</title>
<script type="text/javascript">
	window.onload = function() {
		var save = document.getElementById('save');
		var load = document.getElementById('load');
		
		// 데이터 저장, 이벤트 연결
		save.onclick = function() {
			var text = document.getElementById('text');
			localStorage.setItem('name', text.value); // setItem() 메서드를 통해 로컬 스토리지에 데이터를 key와 value의 쌍으로 저장함
			text.value = ''; // 입력 칸 초기화
		}
		
		// 저장된 데이터 읽기, 이벤트 연결
		load.onclick = function() {
			var loadedName = localStorage.name; // key를 통해 로컬 스토리지에 저장된 데이터의 value를 읽어옴
			alert('localStorage 객체에 저장된 이름 : ' + loadedName);
		}
	};
</script>
</head>
<body>
	<input type="text" id="text"><br>
	<button id="save">저장</button>
	<button id="load">불러오기</button>
</body>
</html>
  1. 새 HTML 파일 s02_localStorage.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로컬 스토리지</title>
<script type="text/javascript">
	window.onload = function() {
		// 저장된 설정 값 읽어오기
		load_setting();
		
		// 이벤트 연결
		document.getElementById('form').onsubmit = function(event) { // submit 이벤트는 <form> 태그에서 발생
			event.preventDefault(); // 기본 이벤트 제거
			save_setting(); // 설정 값 저장
		};
		
		// <input> 태그의 value 속성이 변경되면 실시간으로 스타일에 반영
		document.getElementById('form').oninput = function() {
			apply_setting();
		}
		
		// 로컬 스토리지와 태그의 설정 값을 초기화
		document.querySelector('button').onclick = function() {
			remove_setting();
		}
	};

	// 로컬 스토리지에서 저장된 설정 값을 (태그에) 반환
	function load_setting() {
		document.getElementById('bg_color').value = localStorage.getItem('bg_color');
		document.getElementById('text_color').value = localStorage.getItem('text_color');
		document.getElementById('text_size').value = localStorage.getItem('text_size');
		
		apply_setting();
	}
	
	// 로컬 스토리지에 (태그의) 설정 값을 저장
	function save_setting() {
		localStorage.setItem('bg_color', document.getElementById('bg_color').value);
		localStorage.setItem('text_color', document.getElementById('text_color').value);
		localStorage.setItem('text_size', document.getElementById('text_size').value);
		
		apply_setting();
	}
	
	// 설정 값을 스타일에 반영
	function apply_setting() {
		document.body.style.backgroundColor = document.getElementById('bg_color').value;
		document.body.style.color = document.getElementById('text_color').value;
		document.body.style.fontSize = document.getElementById('text_size').value;
	}
	
	// 로컬 스토리지와 태그의 설정 값을 초기화
	function remove_setting() {
		localStorage.removeItem('bg_color');
		localStorage.removeItem('text_color');
		localStorage.removeItem('text_size');
		
		document.getElementById('bg_color').value = '';
		document.getElementById('text_color').value = '#000000';
		document.getElementById('text_size').value = '16px';
		
		apply_setting();
	}
</script>
</head>
<body>
	<h2>환경 설정 값 기억</h2>
	<form id="form">
		<fieldset> <!-- 그룹화 -->
			<legend>색상/글자 크기 선택</legend> <!-- 그룹 제목 -->
			<ul>
				<li>
					<label for="bg_color">배경색</label>
					<input type="text" name="bg_color" id="bg_color">
				</li>
				<li>
					<label for="text_color">글자색</label>
					<input type="color" name="text_color" id="text_color">
				</li>
				<li>
					<label for="text_size">글자색</label>
					<select name="text_size" id="text_size">
						<option>16px</option>
						<option>20px</option>
						<option>24px</option>						
					</select>
				</li>
			</ul>
			<input type="submit" value="저장">
			<button>초기화</button>
		</fieldset>
	</form>
</body>
</html>

7-1 세션 스토리지

  1. 새 HTML 파일 s03_sessionStorage.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션 스토리지</title>
<script type="text/javascript">
/* 
세션 스토리지 : 브라우저가 열려 있는 동안 모든 데이터를 기억하고 있다가 탭 또는 창을 닫으면 모두 지워지는 저장 공간
*/
	window.onload = function() {
		// 저장된 값 읽어오기
		load();
		
		// 이벤트 연결
		document.getElementById('save').onclick = function() {
			sessionStorage.setItem('name', document.getElementById('first').value); // 세션 스토리지에 저장
			load(); // 저장된 값 읽어오기
		};
		
	};
	
	// 세션 스토리지에 저장된 데이터 읽기
	function load() {
		var display = document.getElementById('display');
		var name = sessionStorage.name; // getItem() 메서드에 key를 인자로 전달하는 것과 같음
		
		if(name) { // 변수 name에 데이터가 저장되어 있으면 true 
			display.innerHTML = '저장된 값 : ' + name;
		}
		else { // 변수 name에 undefined/null/빈 문자열이 저장되어 있으면 false
			display.innerHTML = '비어 있음';
		}
	}
</script>
</head>
<body>
	<h1>세션 스토리지(Session Storage)</h1>
	<input type="text" name="first" id="first">
	<button id="save">저장</button>
	<div id="display">비어 있음</div>
</body>
</html>

8. File API

8-1 <input type="file">의 프로퍼티 목록

8-3 FileReader 객체를 이용한 파일 데이터 읽기

  1. 새 폴더 ch18-file 생성하고 새 HTML 파일 s01_file.html 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>file</title>
<script type="text/javascript">
	window.onload = function() {
		// 이벤트 연결
		document.getElementById('file').onchange = function() { // 파일을 선택할 때 <input> 태그에서 change 이벤트 발생
			var file = this.files[0]; // <input type="file"> 사용시 multiple 속성을 지정하면 복수의 파일을 전송할  있기 때문에 복수의 파일에 대응하기 위해 파일 정보를 배열로 관리; 인덱스를 통해 선택한 파일 각각에 접근 가능
			if(file) alert(file.name + '을 선택했습니다.');
		};
		
		// 이벤트 연결
		document.getElementById('btnStart').onclick = function() {
			readProcess();
		};
	};
	
	function readProcess() {
		var file = document.getElementById('file').files[0]; // 선택한 파일에 대한 정보를 File 객체로 반환
		
		if(!file) { // 파일을 선택하지 않은 경우; file == undefined이면 true
			alert('파일을 선택하세요!');
			return; // 함수를 빠져나감
		}
		
		// File 객체의 속성을 통해 파일의 정보 읽기
		document.getElementById('filename').textContent = file.name; // 파일명
		document.getElementById('filesize').textContent = '(' + file.size + 'bytes)'; // 파일의 용량
		document.getElementById('filetype').textContent = file.type; // 파일의 MIME 타입
		document.getElementById('filedate').textContent = file.lastModifiedDate.toLocaleString(); // 파일의 마지막 갱신 날짜를 사용자의 locale 포맷으로 표시
		
		// FileReader 객체를 통해 파일의 내용 읽기
		var reader = new FileReader();
		var encodeList = document.getElementById('encoding'); // 선택한 인코딩 방식 읽기
		reader.readAsText(file, encodeList.value); // 선택한 파일을 읽어 문자열로 저장; 첫 번째 인자는 File 객체, 두 번째 인자는 인코딩 방식
		reader.onload = function() { // 파일의 내용을 전부 읽어들이면 load 이벤트가 발생하고 onload 속성에 대입된 함수가 실행됨
			document.getElementById('contents').value = reader.result; // 읽어들인 파일의 내용을 <textarea> 태그에 저장
		};
	}
</script>
</head>
<body>
	<h2>현재 시스템의 파일 읽기</h2>
	<input type="file" id="file" accept="text/*">
	<select id="encoding">
		<option>EUC-KR</option>
		<option>UTF-8</option>
	</select>
	<button id="btnStart">읽기</button>
	<br>
	<div>
		<span id="filename">파일명</span>
		<span id="filesize">파일 크기</span>
		<span id="filetype">파일 타입</span>
		<span id="filedate">파일의 마지막 갱신 일시</span>
	</div>
	<textarea rows="10" cols="50" id="contents" readonly></textarea>
</body>
</html>

다음으로