Nice programing

요소 변형 회전 애니메이션

nicepro 2020. 10. 8. 19:00
반응형

요소 변형 회전 애니메이션


jQuery를 사용하여 요소를 어떻게 회전 .animate()합니까? 현재 불투명도를 올바르게 애니메이션하는 아래 줄을 사용하고 있지만 CSS3 변환을 지원합니까?

$(element).animate({
   opacity: 0.25,
   MozTransform: 'rotate(-' + -amount + 'deg)',
   transform: 'rotate(' + -amount + 'deg)'
});

내가 아는 한 기본 애니메이션은 숫자가 아닌 CSS 속성에 애니메이션을 적용 할 수 없습니다.

단계 함수와 사용자 브라우저에 적합한 css3 변환을 사용하여이 작업을 수행 할 수 있다고 생각 합니다. CSS3 변환은 모든 브라우저를 다루기에는 약간 까다 롭습니다 (예를 들어 IE6에서는 Matrix 필터를 사용해야 함).

편집 : 다음은 웹킷 브라우저 (Chrome, Safari)에서 작동하는 예입니다. http://jsfiddle.net/ryleyb/ERRmd/

IE9 만 지원하려는 경우 transform대신을 사용 -webkit-transform하거나 -moz-transformFireFox를 지원할 수 있습니다 .

사용되는 트릭은 우리가 신경 쓰지 않는 CSS 속성 ( text-indent) 을 애니메이션 한 다음 step 함수에서 해당 값을 사용하여 회전을 수행하는 것입니다.

$('#foo').animate(
..
step: function(now,fx) {
  $(this).css('-webkit-transform','rotate('+now+'deg)'); 
}
...

Ryley의 대답 은 훌륭하지만 요소 내에 텍스트가 있습니다. 다른 모든 것과 함께 텍스트를 회전하기 위해 텍스트 들여 쓰기 대신 border-spacing 속성을 사용했습니다.

또한 요소의 스타일에서 약간을 명확히하기 위해 초기 값을 설정합니다.

#foo {
    border-spacing: 0px;
}

그런 다음 애니메이션 청크에서 최종 값 :

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('transform','rotate('+now+'deg)');  
    },
    duration:'slow'
},'linear');

제 경우에는 시계 반대 방향으로 90도 회전합니다.

다음은 라이브 데모 입니다.


제 생각에 jQuery animatetransition2D 또는 3D 속성에서 이러한 애니메이션을 수행 하는 CSS3에 비해 약간 과도하게 사용 됩니다. 또한 브라우저에 남겨두고 JavaScript라는 레이어를 잊어 버리면 특히 애니메이션을 사용하고 싶을 때 CPU를 절약 할 수 있습니다 . 따라서 JavaScript로 기능을 정의하기 때문에 스타일 정의가있는 애니메이션을 좋아합니다 . JavaScript에 더 많은 프레젠테이션을 삽입할수록 나중에 더 많은 문제에 직면하게됩니다.

addClass애니메이션을 적용하려는 요소 를 사용 하기 만하면 CSS transition속성 이있는 클래스를 설정할 수 있습니다. 당신은 단지 애니메이션 "활성화" 숙박은, 순수한 프리젠 테이션 계층에서 구현을 .

.js

// with jQuery
$("#element").addClass("Animate");

// without jQuery library
document.getElementById("element").className += "Animate";

하나는 easly 수 와 jQuery 클래스를 제거 하거나 라이브러리없이 클래스를 제거합니다 .

.css

#element{
    color      : white;
}

#element.Animate{
    transition        : .4s linear;
    color             : red;
    /** 
     * Not that ugly as the JavaScript approach.
     * Easy to maintain, the most portable solution.
     */
    -webkit-transform : rotate(90deg);
}

.html

<span id="element">
    Text
</span>

이것은 대부분의 사용 사례에 빠르고 편리한 솔루션입니다.

다른 스타일 (대체 CSS 속성)을 구현하고 글로벌 .5s 애니메이션으로 즉석에서 스타일을 변경하고 싶을 때도 이것을 사용합니다. 다음 BODY과 같은 형식으로 대체 CSS를 사용하면서에 새 클래스를 추가합니다 .

.js

$("BODY").addClass("Alternative");

.css

BODY.Alternative #element{
    color      : blue;
    transition : .5s linear;
}

This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class.


To add to the answers of Ryley and atonyc, you don't actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property. It might be a good idea to use something that does not risk becoming an actual CSS property in the future.

Also, somebody asked how to animate other things at the same time. This can be done as usual, but remember that the step function is called for every animated property, so you'll have to check for your property, like so:

$('#foo').animate(
    {
        opacity: 0.5,
        width: "100px",
        height: "100px",
        myRotationProperty: 45
    },
    {
        step: function(now, tween) {
            if (tween.prop === "myRotationProperty") {
                $(this).css('-webkit-transform','rotate('+now+'deg)');
                $(this).css('-moz-transform','rotate('+now+'deg)'); 
                // add Opera, MS etc. variants
                $(this).css('transform','rotate('+now+'deg)');  
            }
        }
    });

(Note: I can't find the documentation for the "Tween" object in the jQuery documentation; from the animate documentation page there is a link to http://api.jquery.com/Types#Tween which is a section that doesn't appear to exist. You can find the code for the Tween prototype on Github here).


Just use CSS transitions:

$(element).css( { transition: "transform 0.5s",
                  transform:  "rotate(" + amount + "deg)" } );

setTimeout( function() { $(element).css( { transition: "none" } ) }, 500 );

As example I set the duration of the animation to 0.5 seconds.

Note the setTimeout to remove the transition css property after the animation is over (500 ms)


For readability I omitted vendor prefixes.

This solution requires browser's transition support off course.


I stumbled upon this post, looking to use CSS transform in jQuery for an infinite loop animation. This one worked fine for me. I don't know how professional it is though.

function progressAnim(e) {
    var ang = 0;

    setInterval(function () {
        ang += 3;
        e.css({'transition': 'all 0.01s linear',
        'transform': 'rotate(' + ang + 'deg)'});
    }, 10);
}

Example of using:

var animated = $('#elem');
progressAnim(animated)

//this should allow you to replica an animation effect for any css property, even //properties //that transform animation jQuery plugins do not allow

            function twistMyElem(){
                var ball = $('#form');
                document.getElementById('form').style.zIndex = 1;
                ball.animate({ zIndex : 360},{
                    step: function(now,fx){
                        ball.css("transform","rotateY(" + now + "deg)");
                    },duration:3000
                }, 'linear');
            } 

참고URL : https://stackoverflow.com/questions/5462275/animate-element-transform-rotate

반응형