[jQuery] Animation

Animation


지금까지 학습한 effect는 기본적으로 jQuery에 내장된 함수이다.

만약 height 말고 width를 조절하고 싶은 경우, 컬러를 부드럽게 조절하고 싶은 경우, 스크롤을 부드럽게 움직이게 하는 효과를 주고 싶은 경우 등 개인적으로 커스터마이징하여 요소에 효과를 주고 싶을 때,

jQuery는 이러한 것들을 해결할 수 있는 함수를 제공해주는 데 그것이 바로 animate() 함수이다.


.animate(properties [, duration] [, easing] [, complete]) returns: jQuery

- properties: 움직임을 만들어 낼 수 있는 CSS 속성들

- duration: 애니메이션 시간

- easing: 애니메이션에 가.감속을 조절

- complete: 애니메이션이 모두 멈춘 후에 실행될 콜백 함수


1. properties

첫 번째 오는 매개 변수인 properties는 애니메이션의 속성과 값을 설정한다.

형식은 Object로 아래와 같이 표현한다.

{ property:value; property:value, ......}

property에는 CSS 속성들이 올 수 있지만, 모든 속성이 다 올 수 있는 것은 아니다.

(1) property에 올 수 있는 값

숫자를 사용할 수 있는 CSS 속성으로, border, margin, padding, height, width, font-size, bottom, left, top, right, line height 등과 같은 픽셀이 아닌 em과 % 같은 값들도 지원해준다.

scrollTop, scrollLeft 애니메이션 효과에 적용할 수 있다.


(2) property에 올 수 없는 값

수치형이 아닌 속성 값에는 애니메이션 효과를 줄 수 없다. background-color, 축약형 표현 방법에는 border: "px solid black" 등이 있다.

그러나 jQuery UI plugin 기능을 사용하면 color도 애니메이션을 구현할 수 있다.


2. 애니메이션의 다양한 표현 방법

.animate({fontSize:"2em"}, 3000} = .animate({"font-size":"2em"}, 3000} 

요소의 폰트 사이즈를 현재 크기의 2배로, 3초 동안 애니메이션한다.

cf.) font-size가 변수일 경우 fontSize로 표기해야 한다.


.animate({marginLeft:100, margin-right:100} ,"slow"); = .animate({"margin-left":100, "margin-right":100} ,"600"); 

요소의 왼쪽과 오른쪽의 마진을 100px로, 600 밀리세컨드 동안 애니메이션한다.


.animate({width:"30%"},"fast");

요소의 가로 크기를 부모 가로 크기의 30% 크기로, 200밀리세컨드 동안 애니메이션한다.


.animate({width:"200px", height:"200px"},"fast");

요소의 가로 크기를 200px 세로 크기의 200px 크기로, 200밀리세컨드 동안 애니메이션한다.


.animate({left:"+=20"}, 2000, function(){ }

요소의 위치를 현재 위치를 기준으로 2초동안 계속 오른쪽으로 20px만큼 이동한 후, 콜백 함수를 호출한다.


<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title> animate()를 활용한 가로slide  </title>

<!-- jQuery library -->

<script src="jquery-1.7.2.min.js"></script>

<style>

// overflow:hidden를 설정한 이유는 animate() 함수가 width를 조절할 때에 자동으로 overflow:hidden으로 처리하기 때문에 

// width가 조절되고 난 후에도 overflow:hidden 상태를 유지해주기 위해서이다.

 div{ overflow:hidden; width:300px; display:inline;}

</style>

</head>

<body>

<div>

<img src="sample1.jpg" alt="" width="300" height="307"/>

</div>

<button id ="up">slide감추기</button>

<button id ="down">slide보이기</button>


<!---------- jQuery code Start ---------->

<script>

$('#up').click(function() {

  // #up 버튼을 클릭하면 1초 동안 div 요소의 width가 0px로 변경된다.

  $('div').animate({width:"0px"},1000);  

});

$('#down').click(function() {

  // #up 버튼을 클릭하면 1초 동안 div 요소의 width가 300px로 변경된다.

  $('div').animate({width:"300px"},1000);  

});

</script>

</body>

</html>

cf.) 기본 효과에는 이러한 기능이 없기 때문에 animate() 함수로 처리하였다. 

한 가지 중요한 사실은 slideUp() 이나 slideDown() 함수와 같이 효과가 끝나면 display 상태를 none이나 block으로 변경해주는데,

animate() 함수는 display() 함수는 display 상태를 변경하지 않는다는 것이다.


3. 애니메이션 큐

애니메이션 큐는 여러 개의 애니메이션이 실행을 기다리는 대기열을 의미한다.


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title> animate_queue  </title>

<script src="jquery-1.7.2.min.js"></script>

</head>

<title>Untitled Document</title>

<style type="text/css">

div {

background: #6699FF;

height: 100px;

width: 100px;

position: relative;

}

</style>

</head>


<body>

<p><a href="#" class="run">animate</a></p>

<div> </div>


<!---------- jQuery code Start ---------->

<script>

$("a").click(function(e) {

    // 불투명도 0.5로, 현재 위치에서 오른쪽으로 400만큼씩 2초 동안 이동한다.

    $("div").animate({opacity: "0.5", left: "+=400"}, 2000);

// 현재 위치에서 위에서부터 밑으로 100만큼씩 1초 동안 이동한다.

$("div").animate({top:"+=100"}, 1000);

//slideUp() 함수를 사용하여 height가 줄어들며 접히는 모습을 보여준다. 매개변수가 없을 때에는 'normal'은 0.4초를 의미한다.

$("div").slideUp();

});

</script>

</body>

</html>

jQuery는 위에 있는 세 가지의 animated() 함수를 동시에 실행하지 않고 하나씩 끝나기를 기다리면서 순서대로 실행된다.

animated() 함수는 큐에 들어온 순서대로 실행되기 때문에 제일 먼저 들어온 animated() 함수가 제일 먼저 실행되고 큐에서 제거된다.


cf.) 체이닝

jQuery는 메서드를 연속하여 나열할 수 있는 방법을 제공한다. 이 세 가지의 메서드는 아래와 같이.(dot)로 계속 기술할 수 있는데, 이를 '체이닝'이라고 부른다.

$("div").animated({opacity:"0.1", left:"+=400"}, 2000)

.animated({top:+=100"}, 1000)

.slideUp();


4. 애니메이션 정지

마우스 오버를 하면 opacity가 1로 애니메이션되고, 마우스 아웃을 하면 opacity가 0.3으로 애니메이션되는 이미지가 있다고 가정하자.

사용자가 마우스 오버 또는 아웃을 수시로 한다면 애니메이션 큐에 쌓아놓고 끝날 때까지 모두 실행하게 된다. 

따라서 기존 큐에 있는 모든 애니메이션을 지우고 새로운 애니메이션을 가능하도록 하기 위해 jQuery에서는 stop()이라는 함수를 제공한다.

이를 통해 애니메이션을 처음부터 실행할 수 있다.


stop( [clearQueue] [, jumpToEnd]) returns: jQuery


(1) 매개 변수

- clearQueue: 기본 값을 false이며, 큐에 대기 중인 효과들을 삭제할 것인지의 여부를 결정한다.

- jumpToEnd: 기본 값은 false이며, 진행 중인 애니메이션을 완료할 것인지를 결정한다. true이면 현재 진행 중인 애니메이션의 종료 시점으로 이동한다.


stop() 함수가 호출되면, 현재 진행 중인 애니메이션이 즉시 멈춘다. stop() 함수의 매개 변수(2개)에 따라 큐에 대기 중인 애니메이션이난 효과 등에 대한 처리가 조금씩 다르다.

첫 번째 매개 변수의 경우, 큐에 대기하고 있는 효과를 삭제하려면 true, 삭제하지 않고 실행하려면 false로 설정한다. 기본 값은 false이다.

두 번째 매개 변수의 경우, 진행되고 있는 현재 애니메이션을 끝으로 즉시 이동하려면 true, 그렇지 않고 stop() 명령이 수행된 지점에서 멈추고 끝내려면 false로 설정한다.

기본 값은 false이다.


예를 들어, CSS와 animate 사이에 있는 stop() 함수는 애니메이션(opacity 변경) 먼저 진행 중일 경우 애니메이션이 모두 끝나지 않아도 정지시키고 새로운 애니메이션을 작동시키는 것이다.


<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>animate_stop() </title>

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>

<style type="text/css">


div {margin-bottom:50px;}

a{text-decoration:none;}

#box1 {

background: #F00;

height: 50px;

width: 50px;

position: relative;

}

#box2 {

background: #FF0;

height: 50px;

width: 50px;

position: relative;

}

#box3 {

background: #F0F;

height: 50px;

width: 50px;

position: relative;

}

#box4 {

background: #0FF;

height: 50px;

width: 50px;

position: relative;

}

</style>

</head>

<body>

효과 순서<br />

.animate({opacity: "0.1", left: "500"}, 1000)<br />

.animate({opacity: "0.4", top: "0",  left: 0, height: "100", width: "100"}, 1000)<br />

.slideUp(1000)<br />

.slideDown(1000)<br />

.animate({left: "0"}, 1000)<br />

<br />

<br />  

<a href="#" id="startbtn1">효과시작</a> &nbsp; <a href="#" id="stopbtn1">stop(true,true)</a>

<div id="box1"></div>

<a href="#" id="startbtn2">효과시작</a> &nbsp; <a href="#" id="stopbtn2">stop(true,false)</a>

<div id="box2"></div>

<a href="#" id="startbtn3">효과시작</a> &nbsp; <a href="#" id="stopbtn3">stop(false,true)</a>

<div id="box3"></div>

<a href="#" id="startbtn4">효과시작</a> &nbsp; <a href="#" id="stopbtn4">stop(false,false)</a>

<div id="box4"></div>

<script type="text/javascript">

$("#stopbtn1").click(function(){

 $("#box1").stop(true,true)

})

$("#startbtn1").click(function(){

$("#box1").animate({opacity: "0.1", left: "500"}, 1000)

.animate({opacity: "0.4", top: "0",  left:100, height: "100", width: "100"}, 1000)

.slideUp(1000)

.slideDown(1000)

.animate({left: "0"}, 1000)

return false;

});

//----------------------------------------

$("#stopbtn2").click(function(){

 $("#box2").stop(true,false)

})

$("#startbtn2").click(function(){

$("#box2").animate({opacity: "0.1", left: "500"}, 1000)

.animate({opacity: "0.4", top: "0",  left: 100, height: "100", width: "100"}, 1000)

.slideUp(1000)

.slideDown(1000)

.animate({left: "0"}, 1000)

return false;

});

//-------------------------------------------

$("#stopbtn3").click(function(){

 $("#box3").stop(false,true)

})

$("#startbtn3").click(function(){

$("#box3").animate({opacity: "0.1", left: "500"}, 1000)

.animate({opacity: "0.4", top: "0",  left: 100, height: "100", width: "100"}, 1000)

.slideUp(1000)

.slideDown(1000)

.animate({left: "0"}, 1000)

return false;

});

//----------------------------------------------

$("#stopbtn4").click(function(){

 $("#box4").stop(false,false)

})

$("#startbtn4").click(function(){

$("#box4").animate({opacity: "0.1", left: "500"}, 1000)

.animate({opacity: "0.4", top: "0",  left: 100, height: "100", width: "100"}, 1000)

.slideUp(1000)

.slideDown(1000)

.animate({left: "0"}, 1000)

return false;

});

</script>

</body>

</html>

이 예제에서 효과 시작을 누르면 다섯가지의 효과 순서가 작동된다. 이 때 stop() 함수의 매개 변수에 따라 어떻게 정지되는지 확인하자.


5. 애니메이션 연기(지연)

.delay( duration [, queueName]) returns: jQuery

delay() 메서드는 애니메이션  효과 및 기본 효과를 약간 지연시킬 수 있는 방법이다. 하지만 매개 변수 없는 함수들, 즉 show()나 hide()들은 지연되지 않는다.


<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>delay demo</title>

  <style>

  div {

    position: absolute;

    width: 60px;

    height: 60px;

    float: left;

  }

  .first {

    background-color: #3f3;

    left: 0;

  }

  .second {

    background-color: #33f;

    left: 80px;

  }

  </style>

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

 

<p><button>Run</button></p>

<div class="first"></div>

<div class="second"></div>

 

<script>

$( "button" ).click(function() {

  // slideUp() 함수와 fadeIn() 함수 사이를 0.8초 동안 지연시킨다.

  $( "div.first" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

  $( "div.second" ).slideUp( 300 ).fadeIn( 400 );

});

</script>

</body>

</html>

cf.) $("div").slideUp(300).fadeIn(500);

<div> 요소에 0.3초동안 sideUp()을 수행한 후 곧바로 0.5초 동안 fadeIn() 효과를 적용한다.


cp.) 메서드 체인

메서드 체인은 사슬처럼 연결하여 메서드를 처리할 수 있다. 대부분의 jQuery 메서드는 jQuery 객체를 반환한다. 이렇게 반환된 객체에 지속적으로 다른 메서드를 추가하여

작업할 수 있다.

$("div#box").find('span').text("standard dummy").css("color","red");

--> 지속적으로 결과 집합을 유지하면서 메서드를 적용할 수 있다. jQuery 메서드를 연속적으로 수행하는 방식을 '메서드 체인'이라고 한다.


예제1)

<!DOCTYPE html>

<html>

    <head>

        <style>       

                span {

                color:red;

                cursor:pointer;

            }

            div {

                margin:3px;

                width:80px;

                height:80px;

            }

            div {

                background:#f00;

            }

</style>

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

    </head>

    <body>

        <input type="button" id="fadeout" value="fade out" />

        <input type="button" id="fadein" value="fade in" />

        <input type="button" id="hide" value="hide" />

        <input type="button" id="show" value="show" />

        <input type="button" id="slidedown" value="slide down" />

        <input type="button" id="slideup" value="slide up" />

        <input type="button" id="mix" value="mix" />

        <div id="target">

            target

        </div>

        <script>$('input[type="button"]').click( function(e) {

                var $this = $(e.target);

        //$(e.target): 이벤트가 발생한 엘리먼트 반환하니까 예를 들러 id=fadeout을 클릭하면 <input type="button" id="fadeout" value="fade out" />에 대한

                //엘리먼트 object값을 전달

                //->object값을 레퍼로 감싸서 $this에 저장

                switch($this.attr('id')) {

                    case 'fadeout':

                        $('#target').fadeOut('slow');

         //fadeOut('slow'): slow라는 인자는 fadeOut되는 속도를 나타냄, fast나 숫자로 정교하게 작업 가능하다.

                        break;

                    case 'fadein':

                        $('#target').fadeIn('slow');

                        break;

                    case 'hide':

                        $('#target').hide();

                        break;

                    case 'show':

                        $('#target').show();

                        break;

                    case 'slidedown':

                        $('#target').hide().slideDown('slow');

                        break;

                    case 'slideup':

                        $('#target').slideUp('slow');

                        break;

                    case 'mix':

                        $('#target').fadeOut('slow').fadeIn('slow').delay(1000).slideUp().slideDown('slow', function(){alert('end')});

                 //delay(1000): 1초간 애니메이션 정지

            //function(){alert('end'): slideDown()이라는 이벤트가 끝나면 익명함수 호출된다.(일종의 이벤트)

                        break;

                }

            }) 

        </script>

    </body>

</html>


예제2)

<!DOCTYPE html>

<html>

    <head>

        <style>        

            div {

                background-color:#bca;

                width:100px;

                border:1px solid green;

            }

        </style>

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

    </head>

    <body>

        <button id="go">

            &raquo; Run

        </button>

 

        <div id="block">

            Hello!

        </div>

        <script>/* Using multiple unit types within one animation. */

        

/* animate(): 디테일하게 애니메이션 효과를 제어할 수 있음-> 첫번째 인자는 최종적으로 선택된 엘리먼트가 어떤 모습을 하고 있어야 하는가를 나타냄  두번째 인자는 (3000)는 애니메이션 효과가 3초만에 끝난다.*/

            $("#go").click( function() {

                $("#block").animate({

                    width: "300px", // 기본:100px

                    opacity: 0.4,

                    marginLeft: "50px",

                    fontSize: "30px",

                    borderWidth: "10px"

                }, 3000);

            });</script>

    </body>

</html>



'WebFont-end > jQuery' 카테고리의 다른 글

[jQuery] Ajax 기초  (0) 2014.12.07
[jQuery] Chain  (0) 2014.12.07
[jQuery] Effects  (0) 2014.12.07
[jQuery] Event  (0) 2014.12.07
[jQuery] Attribute/CSS  (0) 2014.12.07