본문 바로가기

Frontend/jQuery

JS jQuery (part. 34) - 상대적 애니메이션

animate( ) 메서드 사용으로 현재 상태에서 상대적으로 애니메이션을 적용할 수 있다

 

<style>
  div {
    width: 50px;
    height: 50px;
    background-color: orange;
  }
</style>

<body>
    <div></div>
</body>

 

$(function () {
  $('div').click(function () {
    var width = $(this).css('width');
    var height = $(this).css('height');
  })
});

 

css( ) 메서드로 이벤트 발생 객체의 width 속성과 height 속성을 추출한다

하지만 현재 변수 width와 height는 숫자가 아니라 '50px' 형태의 문자열이다

상대적으로 크기를 추가하려면 숫자로 바꾼 뒤에 더해야 한다

 

parseInt( ) 함수를 사용하면 문자열 '50px'을 숫자 50으로 바꿀 수 있다.

 

$(function () {
  $('div').click(function () {
    var width = $(this).css('width');
    var height = $(this).css('height');

    $(this).animate({
      width: parseInt(width) + 50,
      height: parseInt(height) + 50
    }, 'slow')
  })
});

 


 

jQuery는 사용자의 편의를 위하여 animate( ) 메서드에 정말 유용한 형태의 방법을 제공

+= 연산자나 -= 연산자를 사용하면 상대적으로 속성이 변경된다

 

 

$(function () {
  $('div').click(function () {
    $(this).animate({
    width: '+=50',
    height: '+=50'
    }, 'slow')
  })
});