12일차 jQuery

|

0916 과제

<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title> </title>
    <style>
        body{
            font-size:9pt;
        }
        .panel {
            width:840px;
            height:415px;
            border:1px solid #ccc;
        }
        
        .nav {
            width:840px;
            text-align:center;
        }
        button {
        	margin-top:5px;
        	padding:5px;
        }
    </style>

    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    	
	    $(document).ready(function(){
	    	var n = 1;
	    	var change; // setInterval 변수 선언. clearInterval에서 사용해야함.
	    	
            // 360도 돌음.(이미지 60개 : 번호 1개씩 증가시켜서 빙빙 돌게하면 됨)
	    	$("#play").click(function(){
	    		play();
	    	});
	    	
            // 이전 사진 1개씩
    		$("#prev").click(function(){
		    	prev();
	    	});
    		
            // 다음 사진 1개씩
    		$("#next").click(function(){
				next();
	    	});
    		
    		function play(){
    			var n = $('img').attr('src').substr(0,0); // 사진이름의 숫자를 변수 n으로 선언
    			change = setInterval(function(){
    				if(n>59){ // 60장초과시 1로 초기화
    					n = 1;
    					$('img').attr('src','car_images/'+n+'.jpg');
    				} else {
    					n++;
    					$('img').attr('src','car_images/'+n+'.jpg');
    				}
    			}, 500);
    		}
    		
    		$("#stop").click(function(){
	    		clearInterval(change);
	    	});
    		
    		function prev(){
    			n--;
    			if(n==0){ // 이전으로 돌아갈시 60으로 초기화
    				n=60;
    			}
    			$('img').attr('src','car_images/'+n+'.jpg');
    		}
    		
    		function next(){
    			n++;
    			if(n==60){ // 60개 도달시 1개로 초기화
    				n=1;
    			}
    			$('img').attr('src','car_images/'+n+'.jpg');
    		}
    		
    	})
   	
    </script>
</head>

<body>  
    <div class="panel">
	        <img src="./car_images/1.jpg" id="view">
    </div>
    <div class="nav">
        <button id="play">play</button>
        <button id="stop">stop</button>
        <button id="prev">prev</button>
        <button id="next">next</button>
    </div>
</body>

</html>

 

jQuery this 정리

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>this 정리</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>

/*javaScript에서의 this 정리*/
// 일반함수에서 this : window 객체
// 중첩함수에서 this : window 객체
// 이벤트에서 this : 이벤트를 발생시킨 객체
// 메소드에서 this : 메소드를 호출한 객체
// 메소드 내부 중첩함수에서 this : window 객체 (예외케이스라 암기해야함) ★★★★★

//예제: 일반함수에서 this
	var data=10;
	function outer(){
	   this.data=20; // this는 Window객체
	   data=30;
	   document.write("1. data1 ="+data,"<br>");  //1. data = 30         -- 전역변수           
	   document.write("2. this.data = "+this.data,"<br>"); // 2. this.data = 30   -- 전역변수          
	   document.write("3. window.data = "+window.data,"<br>"); // 3. window.data = 30 -- 전역변수
	}
	outer();

// 예제: 일반중첩함수에서의 this
	var data=10;
	function outer(){
	   // 중첩함수
	   functioninner(){
	        this.data=20;
	        data=30;
	        document.write("1. data1 = "+data,"<br>"); //1. data = 30         -- 전역변수 
	        document.write("2. this.data = "+this.data,"<br>"); // 2. this.data = 30   -- 전역변수 
	        document.write("3. window.data = "+window.data,"<br>"); // 3. window.data = 30 -- 전역변수
	   }
	   inner();
	}
	outer();

// 예제: 이벤트리스너에서 this
	var data=10;
	$(document).ready(function(){
	   // 이벤트리스너 등록
	   $("#myButton").click(function(){
	        this.data=20;
	        data=30;
	        console.log("1. data1 ="+data); // 1. data = 30         -- 전역변수           
	        console.log("2. this.data = "+this.data); // 2. this.data = 20   -- 이벤트 발생시킨 객체
	        console.log("3. window.data = "+window.data); // 3. window.data = 30 -- 전역변수
	   });
	});

// 예제: 메서드에서 this
	var data=10;
	function MyClass() { // 클래스 정의
	   this.data=0; // 프로퍼티 정의
	}
	MyClass.prototype.method1 =function(){ // 메서드 정의
	   this.data=20;
	   data=30;
	   console.log("1. data1 = "+data); // 1. data = 30         -- 전역변수    
	   console.log("2. this.data = "+this.data); // 2. this.data = 20   -- 메서드를 호출한 객체          
	   console.log("3. window.data = "+window.data); // 3. window.data = 30 -- 전역변수
	}
	var my1 = new MyClass(); // 인스턴스 생성
	my1.method1(); // 메서드 호출

// 예제: 메서드내부 중첩함수에서 this
	var data=10; // 클래스 정의
	function MyClass() { // 프로퍼티 정의
	   this.data=0;
	}
	MyClass.prototype.method1=function(){ // 메서드 정의
	   function inner(){
	        this.data=20;
	        data=30;
	        console.log("1. data1 ="+data); // 1. data = 30         -- 전역변수           
	        console.log("2. this.data = "+this.data); // 2. this.data = 30   -- 전역변수
	        console.log("3. window.data = "+window.data); // 3. window.data = 30 -- 전역변수
	   }
	   inner();
	}
	var my1 = new MyClass(); // 인스턴스 생성
	my1.method1(); // 메서드 호출

</script>
</head>
<body>

 <button id="myButton">리스너실행</button>

</body>
</html>

0916 실습

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습0916</title>
<style>

	div{
		width: 50px;
		height: 50px;
		background-color:orange;
		position: relative;
	}
	
	.outer{
		width: 200px;
		height: 200px;
		background: orange;
		padding: 50px;
		margin: 10px;
	}
	
	.inner{
		width: 100%;
		height: 100%;
		background: red;
	}

</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>

	/*문서객체조작*/
	// remove() : 문서객체를 제거(instance 1개씩)
	$(document).ready(function(){
		// $('h1').first().remove(); // 포그바헤딩 사라짐
		// $('div').empty(); //empty() : 문서객체 내부를 비움(전부)
		// $('p').append($('strong')); // p요소 안으로 strong 이동
		$('h1').after($('p')); // h1요소 뒤로 p 이동
	});
	
	//text노드가 없는 문서객체 생성 - 속성을 입력하는 다른 방식
	$(document).ready(function(){
		$('<img/>',{
			src:'car_images/1.jpg',
			width: 350,
			height: 250
		}).appendTo('body');
		// $('<img/>').attr(src:'car_images/1.jpg').appendTo('body'); 로 쓸수도 있다.
	});
	
	/*문서 객체 추가 : 좋은 sample 예제임 ★★★★★★★ */
	//append : 요소 뒤에 컨텐츠/요소 추가
	//prepend : 요소 내용 끝에 컨텐츠/요소 추가
	//after : 요소 뒤에 컨텐츠/요소 추가
	//before : 요소 내용 끝에 컨텐츠/요소 추가
	$(document).ready(function(){
		var content = [
			{name: '포그바', region:'프랑스'},
			{name: '굴리트', region:'네덜란드'},
			{name: '에우제비오', region:'포루투칼'},
		];
		$('div').append(function(index){ // div가 부모
			var item = content[index];
			var output = '';
			output +='<h1>' + item.name + '</h1>';
			output +='<h2>' + item.region + '</h2>';
			return output;
		});
	}); 
	
	/*문서객체복제 - clone */
	$(document).ready(function(){
		$('span').clone().appendTo('h1');
		$("button").click(function(){
			$('body').append($("p:first").clone(true));	
		})
		$("p").click(function(){
			$(this).animate({fontsize: "+=1px"});
		});
	});
	
	// 좋은 예제 tr, td ★★★★★★★ - 자바스크립트 과제시 사용하게 될것.
	$(document).ready(function(){
		var cloneEle = $(".testTd").clone(); // 선택한 요소를 복사
		cloneEle.text("B1"); // 복사한 요소의 text 변경
		
		$(".testTr").append(cloneEle); // 복사한 요소를 tr의 자식 요소로 추가
		/*테이블의 행에 hover 이벤트를 부착*/
		$(".testTr").hover(function(){
			$(this).css("background","#c9c9c9");},
			function(){
				$(this).css("background","#fff");
			});
			$('#btnAction').on("click",function(e){
				var c1 = $('#t1 tr:eq(0)').clone(true);
				$("#t1").append(c1);
		});
	});
	
	/*매개변수 context : 특정부분에 선택자를 적용하고 싶을 때 사용*/
	//context는 selector가 적용하는 범위를 한정
	// event와 함께 사용.
	$(document).ready(function(){
		$('div').click(function(){
			var header = $('h1', this).text(); // h1 tag를 선택하는데 this 범위 내로 한정
			var paragraph = $('p', this).text();
			alert(header + '\n' + paragraph);
		});
	});
	
	/*이벤트 객체 - canvas*/
	// 캔버스처럼 마우스로 선을 그릴수 있음?
	$(document).ready(function(){
		var canvas = document.getElementById('canvas');
		var context = canvas.getContext('2d');
		$(canvas).on({
			mousedown: function(event){ // canvas 위치정보
				var position = $(this).offset();
				var x = event.pageX - position.left;
				var y = event.pageY - position.top;
				
				context.beginPath(); // 경로생성
				context.moveTo(x,y); // 시작좌표
			},
			mouseup: function(event){ // canvas 위치정보를 얻어냄
				var position = $(this).offset();
				var x = event.pageX - position.left;
				var y = event.pageY - position.top;
				
				context.lineTo(x, y); // 끝좌표
				context.stroke(); // 선을 그리다.
			},
		});
	});
	
	/*Event 강제발생*/
	// triger :  이벤트를 강제로 발생시킨다.
	$(document).ready(function(){
	 $('h1').click(function(event, data1, data2){
	   alert(data1 + ':' + data2);
	 });
	 $('h1').eq(1).trigger('click',[273, 52]); // 이벤트를 강제로 발생시킴
	});
	// preventDefault : 기본 이벤트를 제거
	$(document).ready(function(){
	 $("a").click(function(event){
	   event.preventDefault();
	 });
	});
	// stopPropagation : 이벤트 전달을 제거
	$(document).ready(function(){
	 $("span").click(function(event){
	   event.stopPropagation();
	   alert("The span element was clicked.");
	 });
	});
	/*Event Trigger 예제*/
	$(document).ready(function(){
		$("span").on("eventTest",function(event){
			console.log("The Span element.");
		});
		$("p").on("eventTest",function(event){
			console.log("The p element.");
		});
		$("div").on("eventTest",function(event){
			console.log("The div element.");
		});
		$("button").click(function(){
			$("span").trigger("eventTest");
		});
	})
	
	/*마우스 이벤트*/
	// mouseout(요소를 벗어날때), mouseover : 이벤트 버블링 발생O
	// mouseleave(경계내부->경계외부), mouseenter : 이벤트 버블링 발생X
	$(document).ready(function(){
		$('.outer').mouseover(function(){
			$('body').append('<h1>MOUSEOVER</h1>'); // MOUSEOVER : 요소안으로 들어올때
		}).mouseenter(function(){
			$('body').append('<h1>MOUSEENTER</h1>'); //  MOUSEENTER : 경계외부 -> 경계내부
		});
	});
	
	/*키보드 이벤트*/
	// keyup : 키보드를 뗄 때 발생
	// keydown : 키 입력시 발생
	// keypress : 키 입력시 발생. 한글지원안함. alt ctrl shift esc 호출안됨
	$(document).ready(function(){
		$('textarea').keyup(function(){ 
			var inputLength = $(this).val().length; // 남은 글자수를 구함
			var remain = 150 - inputLength;
			$('h1').html(remain); // html() : 문서객체의 내부추가. 문서 객체에 입력
			if(remain >= 0){
				$('h1').css('color', 'black');
			} else {
				$('h1').css('color', 'red');
			}
		})
	})
	
	/*윈도 이벤트
	ready : 문서객체가 준비완료되면
	load : 문서객체를 불러들일때 발생
	unload : 문서객체를 닫을 때 발생 ~ 사용자들 complian 관련 이슈 많음.
	resize : 윈도의 크기를 변경시킬 때 발생
	scroll : 윈도를 스크롤할 때 발생
	error : 에러가 있을 때 발생
	*/
	$(document).ready(function(){ // 무한 스크롤
		$(window).scroll(function(){ // 스크롤 이벤트 발생 시
			var scrollHeight = $(window).scrollTop() + $(window).height();
			var documentHeight = $(document).height();
			// 스크롤의 높이와 문서의 높이가 같을 때 10줄을 추가
			if(scrollHeight == documentHeight){
				for(var i =0; i < 10; i++){
					$('<h1>Infinity Scroll</h1>').appendTo('body');
				}
			}
		});
	});
	//테스트를 위해 내부에 공간을 채워둠.
	$(document).ready(function(){
		for(var i=0; i<20; i++){
			$('<h1>Infinity Scroll</h1>').appendTo('body');
		}
	});
	
	/*입력양식 이벤트*/
	// attr : HTML의 Attribute(tag안의 string값을 가져옴)
	// prop : javascript Property(실제 속성 값을 가져옴.)
	//change 예제
	$(document).ready(function(){
		$('#all-check').change(function(){
			if(this.checked){
				$('#check-item').children().prop('checked', true);
			} else {
				$('#check-item').children().prop('checked', false);
			}
		});
		
		var $checkbox = $('#chk'); 
    	  console.log($checkbox.attr('checked')); // checked : checked해도 값의 변화가 없음.
	      console.log($checkbox.prop('checked')); // true
	});
	
	/*기본시각효과*/
	//toggle 효과 예제
	$(document).ready(function(){
		$('button').click(function(){
			$('page').toggle('show'); // show와 hide가 반복호출
		}); 
	});
	
	// 사용자 정의 효과
	$(document).ready(function(){
		$('div').hover(function(){
			$(this).animate({
				left: 500 // left로 500 이동이 애니메이션처럼
			},'slow');
		}, function(){
			$(this).animate({
				left: 0
			}, 'slow');
		});
	});
	
	//animate 예제
	$(document).ready(function(){
		$("#btn").click(function(){
			$("#box").animate({
				width: "400px"
			}, {
				duration: 5000,
				easing: "linear",
				step: function(x){ // 한 단계마다 함수호출
					$("#demo").text(Math.round(x*100/400)+"%");
				}
			});
		});
	});

</script>
</head>
<body>
<!-- 
	<br><br>------------------remove() empty()----------------<br><br>
	<h1>포그바 헤딩</h1>
	<h1>지단 헤딩</h1>
	<br><br>------------------p요소 안으로 strong 이동----------------<br><br>
	<p>헤딩슛 </p>
	<strong>골</strong>
	<br><br>------------------h1요소 뒤로 p 이동----------------<br><br>
	<p>날강두</p>
	<h1>빠염</h1>
	
	<br><br>------------------문서 객체 추가----------------<br><br>
	<div></div>
	<div></div>
	<div></div>
	 
	<br><br>------------------문서 객체 복제----------------<br><br>
	<div>
		<h1></h1>
		<p><span>박지성</span></p>
	</div>
	<button>글자크기 증가</button>
	
	<br><br>------------------좋은 예제 tr, td----------------<br><br>
	<table id="t1">
	   <tr class="testTr">
	      <td class="testTd">A1</td>
	   </tr>
	 </table>
	 <br/>
	 <input type="button" value="행추가" id="btnAction">
	
	<br><br>------------------/*이벤트 객체 - canvas*/----------------<br><br>
	<canvas id="canvas" width="700" height="400" style="border: 5px solid black">
	</canvas>
	
	<br><br>------------------/*Event Trigger 예제*/----------------<br><br>
	<div style="height:100px;width:500px;background-color:lightblue;">
	  This is a div element.
	 <p style="background-color:pink">This is a p element <br>
	   <span style="background-color:orange">This is a span element</span>
	 </p>
	</div>
	<button>Event Trigger</button>
		
	<br><br><a href="https://naver.com">-----------------/*마우스 이벤트*/----------------</a><br><br>		
	<div class="outer">
		<div class="inner"></div>
	</div>
	
	<br><br>------------------/*키보드 이벤트*/---------------<br><br>
	<div>
		<p>지금 내 생각을</p>
		<h1>150</h1>
		<textarea cols="70" rows="5">/</textarea>
	</div>
	
	
	<br><br>------------------/*입력양식 이벤트*/ - change 예제---------------<br><br>
	<input type="checkbox" name="" id="chk" checked="checked">
	<input type="checkbox" id="all-check"/>
	<label>ALL</label>
	<div id="check-item">
		<input type="checkbox"/>
		<label>A option</label>
		<input type="checkbox"/>
		<label>B option</label>
		<input type="checkbox"/>
		<label>C option</label>
	</div>
	
	<br><br>------------------기본시각효과 - toggle 효과 예제---------------<br><br>
	<button>toggle show</button>
	<div class="page">
		<h1>77억</h1>
		<p>Alexis Sanchez</p>
	</div>
	
	<br><br>------------------문서 객체 추가----------------<br><br>
	<div></div>
	<div></div>
	<div></div>-->
	
	<br><br>------------------//animate 예제----------------<br><br>
	<button id="btn">Start Progress Bar</button>
	 <div style="border:1px solidgreen;margin:10px;width:400px;">
	   <div id="box"style="background:#98bf21;height:50px;width:1px;border:1px solidgreen;"></div>
	 </div>
	 <p id="demo"></p>
	

</body>
</html>

jQuery 슬라이드 예제

<!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0px; padding:0px; }
        /* Animation Canvas */
        .animation_canvas  {
            overflow:hidden;
            position:relative;           
            width:600px; height:400px;
        }
    
        /* Slider Panel */
        .slider_panel { width:3000px; position:relative; }
        .slider_image { float:left; width:600px; height:400px; }
    
        /* Slider Text Panel */
        .slider_text_panel { position:absolute; top:200px; left:50px; }
        .slider_text { position:absolute; width:250px; height:150px; }
    
        /* Control Panel */
        .control_panel  {
            position:absolute; top:380px; 
            left:270px; height:13px; 
            overflow:hidden; 
        }

        .control_button {
            width:12px; height:46px;
            position:relative; 
    
            float:left; cursor:pointer;  
            background:url('point_button.png');
        }
        .control_button:hover { top:-16px; }
        .control_button.active { top:-31px; }
    </style>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function () {
            // 슬라이더를 움직여주는 함수
            function moveSlider(index) {
                // 슬라이더를 이동합니다.
                var willMoveLeft = -(index * 600);
                $('.slider_panel').animate({ left: willMoveLeft }, 'slow');

                // control_button에 active클래스를 부여/제거합니다.
                $('.control_button[data-index=' + index + ']').addClass('active');
                $('.control_button[data-index!=' + index + ']').removeClass('active');

                // 글자를 이동합니다.
                $('.slider_text[data-index=' + index + ']').show().animate({
                    left: 0
                }, 'slow');
                $('.slider_text[data-index!=' + index + ']').hide('slow', function () {
                    $(this).css('left', -300);
                });
            }

            // 초기 텍스트 위치 지정 및 data-index 할당
            $('.slider_text').css('left', -300).each(function (index) {
                $(this).attr('data-index', index);
            });

            // 컨트롤 버튼의 클릭 핸들러 지정 및 data-index 할당
            $('.control_button').each(function (index) {
                $(this).attr('data-index', index);
            }).click(function () {
                var index = $(this).attr('data-index');
                moveSlider(index);
            });

            // 초기 슬라이더 위치 지정
            var randomNumber = Math.round(Math.random() * 5);
            moveSlider(randomNumber);
        });
    </script>
</head>
<body>
    <h1>Test Header</h1>
    <div class="animation_canvas">
        <div class="slider_panel">
            <img src="Desert.jpg" class="slider_image"/>
            <img src="Hydrangeas.jpg" class="slider_image"/>
            <img src="Jellyfish.jpg" class="slider_image"/>
            <img src="Koala.jpg" class="slider_image"/>
            <img src="Lighthouse.jpg" class="slider_image"/>
        </div>
        <div class="slider_text_panel">
            <div class="slider_text">
                <h1>Lorem ipsum</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            </div>
            <div class="slider_text">
                <h1>Nulla eget</h1>
                <p>Nulla eget sapien mauris, ornare elementum elit.</p>
            </div>
            <div class="slider_text">
                <h1>Quisque eleifend</h1>
                <p>Quisque eleifend augue nec lacus lobortis porta.</p>
            </div>
            <div class="slider_text">
                <h1>Donec</h1>
                <p>Donec a ligula lectus, eu iaculis justo.</p>
            </div>
            <div class="slider_text">
                <h1>Vivamus scelerisque</h1>
                <p>Vivamus scelerisque mauris id nunc dictum sit amet.</p>
            </div>
        </div>
        <div class="control_panel">
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
        </div>
    </div>
    <h1>Test Header</h1>
</body>
</html>

화면이 슬라이드 스르륵

'Bitcamp > BITCAMP - Front Web' 카테고리의 다른 글

IBSheet 그리드 특강  (0) 2019.09.26
미니 프로젝트  (0) 2019.09.17
11일차 jQuery  (0) 2019.09.11
JavaScript - LinkedList, nodeType(재귀), Event 핸들러, DOM  (0) 2019.09.10
JavaScript - Object 객체, DOM  (0) 2019.09.09
And