jQuery 공작소 : .animate()

jQuery 공작소에 방문해 주셔서 감사드립니다. 쉬운 예제로 느껴보세요!!

animate 메소드는 CSS 속성 값을 조절하여 애니메이션 효과를 구현합니다.

예제 1
이미지에 크기조절 애니메이션 적용해 보기 (px 단위)
보기
버튼을 누르면 이미지의 크기가 바뀝니다.


소스
<style type="text/css">
    .css_test {
        height : 430px;
        text-align : center;
    }
    .css_test img {
        width : 500px;
    }
</style>

<div class="css_test">
    버튼을 누르면 이미지의 크기가 바뀝니다.<br>
    <button onclick="$('[name=j_test]').animate({width : 100})" type="button">가로 100px</button>
    <button onclick="$('[name=j_test]').animate({width : '300'})" type="button">가로 300px</button>
    <button onclick="$('[name=j_test]').animate({'width' : '500px'})" type="button">가로 500px</button><br><br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/2570B33354D74FB12F" />
</div>
관련 CSS
jQuery

animate( { width : 100 } )
animate( { width : '300' } )
animate( { 'width' : '500px' } )

※ 위 형식 모두 사용가능

예제 2
이미지에 크기조절 애니메이션 적용해 보기 (%단위)
보기
버튼을 누르면 이미지의 크기가 바뀝니다.


소스
<style type="text/css">
    .css_test {
        text-align : center;
    }
    .css_test img {
        width : 500px;
    }
</style>

<div class="css_test">
    버튼을 누르면 이미지의 크기가 바뀝니다.<br>
    <button onclick="$('[name=j_test]').animate({'width' : '50%'})" type="button">가로 50%</button>
    <button onclick="$('[name=j_test]').animate({'width' : '100%'})" type="button">가로 100%</button><br><br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/224D643854D74C4F15" />
</div>
관련 CSS
jQuery

animate( { 'width' : '50%' } )
animate( { 'width' : '100%' } )

예제 3
애니메이션 여러번 실행하기 (순차적 실행)
보기


소스
<style type="text/css">
    .css_test {
        height : 450px;
        text-align : center;
    }
</style>

<div class="css_test">
    <button onclick="j_test_click()" type="button">눌러보세용</button><br><br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/25469641555AC5000B" width="500" />    
</div>

<script type="text/javascript">
    // 애니메이션은 순차적으로 실행됩니다
    // 아래 애니메이션은 동시에 실행되지 않습니다
    function j_test_click(){
        $('[name=j_test]').stop(); // 실행중인 애니메이션을 멈춘다 (버튼 연타에 대비한 중복실행 방지)
        $('[name=j_test]').animate({width:100}); // 실행 후 아래 실행
        $('[name=j_test]').animate({width:200}); // 실행 후 아래 실행
        $('[name=j_test]').animate({width:50}); // 실행 후 아래 실행
        $('[name=j_test]').animate({width:500});
    }
</script>
관련 CSS
jQuery
- 애니메이션은 예약(Queue)이 적용되어 동시에 실행되지 않습니다.
- 하나가 끝나고 다음것이 실행됩니다.
예제 4
동시에 두가지 이상 애니메이션 실행 1
보기


소스
<style type="text/css">
    .css_test {
        height : 450px;
        text-align : center;
    }
</style>

<div class="css_test">
    <button onclick="j_test_click()" type="button">시작!</button>
    <button onclick="j_test_init()" type="button">복원</button><br><br>
    <img name="j_test2" src="https://t1.daumcdn.net/cfile/tistory/230D9C3454D7331920" />
</div>

<script type="text/javascript">
    function j_test_click(){
        $('[name=j_test2]').stop();
        $('[name=j_test2]').animate( { width:500, height:2 } ); // 동시에 두가지 실행
        $('[name=j_test2]').animate( { width:0 } );
    }

    function j_test_init(){
        $('[name=j_test2]').stop().css( { width:'auto', height:'auto' } ); // css 메서드 사용
    }
</script>
관련 CSS
jQuery

animate( { width : 500, height : 2 } )
- 위 처럼 사용하면 동시에 애니메이션이 실행됩니다.

예제 5
동시에 두가지 이상 애니메이션 실행 2
보기


소스
<style type="text/css">
    .css_test {
        height : 450px;
        text-align : center;
    }
</style>

<div class="css_test">
    <button onclick="j_test_click()" type="button">시작!</button>
    <button onclick="j_test_init()" type="button">복원</button><br><br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/2515ED4854D735161E" />
</div>

<script type="text/javascript">
    function j_test_click(){
        $('[name=j_test]').stop().animate({
            width:50,
            height:50,
            opacity:0.2 // 투명도 설정(소수점 단위) : 1 - 불투명, 0 - 투명
        }); // 줄바꿈해서 보기편하게 코딩! 마지막은 , 를 붙이지 않습니다.(자주하는 실수)
    }

    function j_test_init(){
        // css 메서드 사용
        $('[name=j_test]').stop().css({
            width:'auto',
            height:'auto'
        }).animate({
            opacity:1
        });
    }
</script>
관련 CSS
jQuery

- 이미지 애니메이션
$( '[name=j_test]' ).stop().animate( {
        width : 100,
        height : 100,
        opacity : 0.2
} );
 
- 이미지 복원
$( '[name=j_test]' ).stop().css( {
        width : 'auto',
        height : 'auto'
} ).animate( {
        opacity : 1
} );

예제 6
이미지 테두리를 둥글게 만들어 보기 - 아래 사진에 마우스를 올려보세요~!
보기
물컹 물컹 이미지 : 마우스를 올려보세요.
jQuery UI 의 움직임 효과를 추가로 사용하였습니다.


소스
<style type="text/css">
    .css_test {
        text-align : center;
    }
    .css_test img {
        border-radius : 0;
        margin-bottom : 10px;
    }
</style>

<div class="css_test">
    물컹 물컹 이미지 : 마우스를 올려보세요.<br>
    jQuery UI 의 움직임 효과를 추가로 사용하였습니다.<br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/216F4139550B923E33" /><br>
    <img name="j_test" src="https://t1.daumcdn.net/cfile/tistory/213D684C550B9B3B0D" /><br>
</div>

<script type="text/javascript">
    function j_test_mover(o){
        $(o).stop().animate({'border-radius':120}, 1000, 'easeOutElastic');
    }

    function j_test_mout(o){
        $(o).stop().animate({'border-radius':1});
    }

    $('[name=j_test]').bind('mouseover', function(){
        j_test_mover(this);
    }).bind('mouseout', function(){
        j_test_mout(this);
    });
</script>
관련 CSS
jQuery

animate( { 'border-radius' : 120 }, 1000, 'easeOutElastic' )

- CSS border-radius 속성을 조절해서 물컹이는(?) 애니메이션을 적용한 예제입니다.
- border-radius 속성은 " - " 가 포함되어있어서 따옴표로 묶어주어야 합니다.
- 변수명에 - 는 사용할 수 없습니다.

- 1000 은 애니메이션이 실행되는 시간입니다. 1000 은 1초.
- 'easeOutElastic' 은 움직임 효과입니다. 제이쿼리UI를 추가로 사용해야 적용가능.

참고 자료 : easing(이징) 효과 모음

예제 7
애니메이션이 실행되는 시간 정하기
보기

아래 자동차를 클릭해 보세요.






소스
<style type="text/css">
    .css_test {
        margin : 20px auto 0 auto;
        text-align : right;
        width : 550px;
    }
    .css_test img {
        cursor : pointer;
        position : relative; /* 이 설정을 해주어야 자동차가 움직입니다 */
    }
</style>

<div class="ac">
    <button type="button" onclick="j_test_comeback()">복귀 버튼</button><br>
    아래 자동차를 클릭해 보세요.
</div>
<div class="css_test">
    <img onclick="j_test_gogo(this, 3000)" src="//superkts.com/img/css/car0194.gif" /><br>
    <img onclick="j_test_gogo(this, 2000)" src="//superkts.com/img/css/car0194.gif" /><br>
    <img onclick="j_test_gogo(this, 1000)" src="//superkts.com/img/css/car0194.gif" /><br>
    <img onclick="j_test_gogo(this, 500)" src="//superkts.com/img/css/car0194.gif" /><br>
    <img onclick="j_test_gogo(this, 250)" src="//superkts.com/img/css/car0194.gif" /><br>
    <img onclick="j_test_gogo(this, 10000)" src="//superkts.com/img/css/car0194.gif" /><br>
</div>

<script type="text/javascript">
    function j_test_gogo(o, n){
        $(o).stop().animate({
            left:-500,
            top:220
        }, n);
    }

    function j_test_comeback(){
        $('.css_test img').stop().animate({
            left:0,
            top:0
        }, 1000, 'easeOutElastic');
    }
</script>
관련 CSS
jQuery

이 예제는 함수를 적절히 활용해서 만들었습니다.

animate( { left : -500, top : 200 }, 500 )  -  0.5 초 동안 애니메이션 실행
animate( { left : -500, top : 200 }, 1000 )  -  1 초 동안 애니메이션 실행
animate( { left : -500, top : 200 }, 2000 )  -  2 초 동안 애니메이션 실행

- 1/1000 초 단위로 값을 지정합니다.
- 10 초라면 10000

예제 8
제이쿼리UI 의 애니메이션 효과보기 (easing 효과정리)
보기
linear swing easeInQuad easeOutQuad easeInOutQuad easeInCubic easeOutCubic easeInOutCubic easeInQuart easeOutQuart easeInOutQuart easeInQuint easeOutQuint easeInOutQuint easeInSine easeOutSine easeInOutSine easeInExpo easeOutExpo easeInOutExpo easeInCirc easeOutCirc easeInOutCirc easeInElastic easeOutElastic easeInOutElastic easeInBack easeOutBack easeInOutBack easeInBounce easeOutBounce easeInOutBounce
위 효과 이름을 눌러보세요. ^^
easeOutBounce 효과가 제일 적절해 보이네요.
소스
<style type="text/css">
    .css_test {
        text-align : center;
    }
    .css_test span { /* 버튼 */
        border-radius : 5px;
        border : 3px solid gray;
        box-shadow : 0 0 3px silver;
        cursor : pointer;
        display : inline-block;
        line-height : 150%;
        margin : 2px 0;
        padding : 3px;
    }
    .css_test .rock { /* 돌 이미지 */
        left : -150px;
        position : relative;
        top : -570px;
        width : 80px;
    }
</style>

<div class="css_test">
    <img src="//superkts.com/img/pisa.gif" style="height:600px;" />
    <img class="rock" src="//superkts.com/img/hobbang06.gif" onclick="alert('저말고 아래 버튼을 눌러주세요. ㅎ')" />
    <div>
        <span onclick="j_test_drop('linear')">linear</span>
        <span onclick="j_test_drop('swing')">swing</span>
        <span onclick="j_test_drop('easeInQuad')">easeInQuad</span>
        <span onclick="j_test_drop('easeOutQuad')">easeOutQuad</span>
        <span onclick="j_test_drop('easeInOutQuad')">easeInOutQuad</span>
        <span onclick="j_test_drop('easeInCubic')">easeInCubic</span>
        <span onclick="j_test_drop('easeOutCubic')">easeOutCubic</span>
        <span onclick="j_test_drop('easeInOutCubic')">easeInOutCubic</span>
        <span onclick="j_test_drop('easeInQuart')">easeInQuart</span>
        <span onclick="j_test_drop('easeOutQuart')">easeOutQuart</span>
        <span onclick="j_test_drop('easeInOutQuart')">easeInOutQuart</span>
        <span onclick="j_test_drop('easeInQuint')">easeInQuint</span>
        <span onclick="j_test_drop('easeOutQuint')">easeOutQuint</span>
        <span onclick="j_test_drop('easeInOutQuint')">easeInOutQuint</span>
        <span onclick="j_test_drop('easeInSine')">easeInSine</span>
        <span onclick="j_test_drop('easeOutSine')">easeOutSine</span>
        <span onclick="j_test_drop('easeInOutSine')">easeInOutSine</span>
        <span onclick="j_test_drop('easeInExpo')">easeInExpo</span>
        <span onclick="j_test_drop('easeOutExpo')">easeOutExpo</span>
        <span onclick="j_test_drop('easeInOutExpo')">easeInOutExpo</span>
        <span onclick="j_test_drop('easeInCirc')">easeInCirc</span>
        <span onclick="j_test_drop('easeOutCirc')">easeOutCirc</span>
        <span onclick="j_test_drop('easeInOutCirc')">easeInOutCirc</span>
        <span onclick="j_test_drop('easeInElastic')">easeInElastic</span>
        <span onclick="j_test_drop('easeOutElastic')">easeOutElastic</span>
        <span onclick="j_test_drop('easeInOutElastic')">easeInOutElastic</span>
        <span onclick="j_test_drop('easeInBack')">easeInBack</span>
        <span onclick="j_test_drop('easeOutBack')">easeOutBack</span>
        <span onclick="j_test_drop('easeInOutBack')">easeInOutBack</span>
        <span onclick="j_test_drop('easeInBounce')">easeInBounce</span>
        <span onclick="j_test_drop('easeOutBounce')">easeOutBounce</span>
        <span onclick="j_test_drop('easeInOutBounce')">easeInOutBounce</span>
    </div>
    위 효과 이름을 눌러보세요. ^^<br>
    easeOutBounce 효과가 제일 적절해 보이네요.
</div>

<script type="text/javascript">
    function j_test_drop(v){ // 돌 낙하
        $('.css_test .rock').stop().css({top:-570}).animate({top:10}, 1000, v);
    }
</script>
관련 CSS
jQuery

- linearswing제이쿼리UI 없이도 사용할 수 있습니다.
- 따로 지정하지 않을때의 기본값은 swing 입니다.

링크 : http://jqueryui.com/

* 제이쿼리 홈페이지의 애니메이션 효과 데모 링크


참고 : easing(이징) 효과 모음
예제 9
애니메이션 종료 후 지정한 함수 호출하기
보기

소스
<style type="text/css">
    .css_test {
        text-align : center;
        height : 500px;
    }
    .css_test img {
        margin-top : 15px;
        opacity : 0;
        width : 0;
    }
</style>

<div class="css_test">
    <button type="button" onclick="j_test_show1()">눌러보세용1</button>
    <button type="button" onclick="j_test_show2()">눌러보세용2</button>
    <button type="button" onclick="j_test_show3()">눌러보세용3</button><br>
    <img src="//superkts.com/img/css/cat.gif" />
</div>

<script type="text/javascript">
    function j_test_init(){ // 이미지 초기화
        $('.css_test img').stop().css({
            width:0,
            opacity:0
        });
    }

    function j_test_show1(){
        j_test_init();
        $('.css_test img').stop().animate({
            width:500,
            opacity:1
        }, 1000, function(){
            alert('냥'); // 함수형태로 바로 실행하기
        });
    }

    function j_test_show2(){
        j_test_init();
        $('.css_test img').stop().animate({
            width:500,
            opacity:1
        }, 1000, j_test_alert2); // 함수 실행 (이름으로)
    }
    function j_test_alert2(){
        alert('냥냥냥');
    }

    function j_test_show3(){
        j_test_init();
        $('.css_test img').stop().animate({
            width:500,
            opacity:1
        }, 1000, function(){
            j_test_alert3('멍멍?'); // 매개변수 넣어 다른함수 호출
        });
    }
    function j_test_alert3(msg){
        alert(msg);
    }

</script>
관련 CSS
jQuery

아래와 같은 방식으로 애니메이션 종료후 함수를 호출할 수 있습니다.

animate({ width : 500, opacity : 1 }, 1000, function(){ alert('냥') } )  -  함수형태로 alert 실행하기
animate({ width : 500, opacity : 1 }, 1000, j_test_alert2 )  -  함수명으로 호출
animate({ width : 500, opacity : 1 }, 1000, function(){ j_test_alert3('멍멍?') } )  -  함수호출시 매개변수 전달

예제 10
상대적인 값 증가, 감소 애니메이션
보기

소스
<style type="text/css">
    .css_test {
        text-align : center;
    }
    .css_test img {
        margin-top : 10px;
        width : 100px;
    }
</style>

<div class="css_test">
    <button type="button" onclick="$('.css_test img').animate({width:'+=50'})">커져라 !!</button>
    <button type="button" onclick="$('.css_test img').animate({width:'-=50'})">작아져라 !!</button><br>
    <img src="https://t1.daumcdn.net/cfile/tistory/27042F3354D74FB30A" />
</div>
관련 CSS
jQuery

animate( { width : '+=50' } )  -  현재 크기에 +50px 만큼 애니메이션
animate( { width : '-=50' } )  -  현재 크기에 -50px 만큼 애니메이션

- 이 예제에는 stop() 메서드를 사용하지 않았습니다.
- 버튼을 연타해서 어떻게 되는지 해보세요 ^^

예제 11
귀신의 공작소 (깜놀 주의 !!)
보기
약간 무서울 수 있습니다. 절대 심장이 약하신 분은 하지 마세요 !!!
소스
<style type="text/css">

    #css_test {
        background-color : black;
        background-repeat : no-repeat;
        height : 550px;
        border-radius : 10px;
    }

    #css_test.ghost1 {
        background-image : url('//superkts.com/img/css/ghost.gif');
        background-position : 50% 50%;
        background-size : 0;
    }

</style>

<script type="text/javascript">

    var chk = false;

    function ghostIn(){
        if(chk) return;
        chk = true;
        $('#css_test').stop().animate({'background-size':'+=80%'}, 500, ghostOut);
    }

    function ghostOut(){
        $('#css_test').stop().animate({'background-size':'-=80%'}, 5000, ghostEnd);
    }

    function ghostEnd(){
        chk = false;
    }

</script>

<div class="bold red ac pd5">약간 무서울 수 있습니다. 절대 심장이 약하신 분은 하지 마세요 !!!</div>
<div id="css_test" class="ghost1"></div>
<div class="mt5 ac">
    <button type="button" onclick="ghostIn()">준비됬으면 누르세요 !</button>
</div>
관련 CSS
jQuery

animate( { 'background-size' : '+=80%' }, 500, ghostOut )  -  귀신이 나오는 애니메이션
animate( { 'background-size' : '-=80%' }, 5000, ghostEnd )  -  귀신이 돌아가는 애니메이션

- 배경이미지에 애니메이션 효과를 적용해 보았습니다.
- 별로 무섭지는 않죠? ㅎ

예제 12
잠깐! toggle 도 있답니다. 버튼을 여러번 눌러보세요.
보기
보였다 안보였다 애니메이션 입니다.

소스
<style type="text/css">
    .css_test {
        text-align : center;
        height : 500px;
    }
    .css_test img {
        margin-top : 10px;
    }
</style>

<div class="css_test">
    보였다 안보였다 애니메이션 입니다.<br>
    <button type="button" onclick="$('.css_test img').stop().animate({width:'toggle'})">toggle 1</button>
    <button type="button" onclick="$('.css_test img').stop().animate({width:'toggle'}, 2000)">toggle 2</button>
    <button type="button" onclick="$('.css_test img').stop().animate({width:'toggle'}, 1000, 'easeInOutElastic')">toggle 3</button>
    <button type="button" onclick="$('.css_test img').stop().animate({width:'toggle'}, 2000, 'easeInOutElastic', function(){ alert('데헷 ^^*') })">toggle 4</button>
    <br>
    <img src="https://t1.daumcdn.net/cfile/tistory/213D5338550B92391D" />
</div>
관련 CSS
jQuery

animate( { width : 'toggle' } )  -  width 값을 0 으로 그리고 다시 원상태로 반복
animate( { width : 'toggle' }, 2000 )  -  2초 동안 실행
animate( { width : 'toggle' }, 1000, 'easeInOutElastic' )  -  easeInOutElastic 효과적용하여 애니메이션
animate( { width : 'toggle' }, 2000, 'easeInOutElastic', function(){ alert('데헷 ^^*') } )  -  애니메이션 종료후 함수 실행

예제 13
글자 크기도 조절해 봅시다 !
보기
제이쿼리 공작소
소스
<style type="text/css">
    .css_test {
        text-align : center;
        height : 150px;
    }
</style>

<button type="button" onclick="$('.css_test').animate({'font-size':'70px'}, 2000, 'easeInOutElastic')">커져라</button>
<button type="button" onclick="$('.css_test').animate({'font-size':'30px'}, 2000, 'easeInOutElastic')">작아져라</button>

<div class="css_test" style="font-size:30px;">
    제이쿼리 공작소
</div>
관련 CSS
예제 14
애니메이션 멈추기 그리고 중복실행 방지
jQuery
- 애니메이션은 멈추는것도 중요합니다.
- 또 중복실행되어 이상한 상황이 되는것도 막아야 하죠.
- 아래 예제를 한번 보시면 좋습니다. ^^

다중 예약 애니메이션 완벽히 멈추기
jQuery 홈페이지 .animate() API 문서 : http://api.jquery.com/animate/