Animating a CSS transform with jQuery

眉间皱痕 提交于 2019-12-03 13:26:55

You can also predefine the rotation in a CSS class and use jQuery to add/remove the class:

CSS:

#my_div {
    -moz-transition: all 500ms ease;
    -o-transition: all 500ms ease;
    -webkit-transition: all 500ms ease;
    transition: all 500ms ease;
}
.rotate {
    -moz-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    transform: rotate(180deg);
}

jQuery:

$("#my_div").addClass('rotate');

Try this:

$('#myDiv').animate({ textIndent: 0 }, {
    step: function(go) {
      $(this).css('-moz-transform','rotate('+go+'deg)');
      $(this).css('-webkit-transform','rotate('+go+'deg)');
      $(this).css('-o-transform','rotate('+go+'deg)');
      $(this).css('transform','rotate('+go+'deg)');
    },
    duration: 500,
    complete: function(){ alert('done') }
});

http://jsfiddle.net/RPSzb/2/

Ignitor

jQuery cannot animate transform properties out of the box. But you can animate custom properties with .animate() and do the transformation "manually" using the step function:

var $myDiv = $("#my_div"),
    ccCustomPropName = $.camelCase('custom-animation-degree');
$myDiv[0][ccCustomPropName ] = 0; // Set starting value
$myDiv.animate({ccCustomPropName : 180},
    {
        duration: 500,
        step: function(value, fx) {
            if (fx.prop === ccCustomPropName ) {
                $myDiv.css('transform', 'rotateY('+value+'deg)');
                // jQuery will add vendor prefixes for us
            }
        },
        complete: function() {
            // Callback stuff here
        }
    });

See this fiddle for a working example (click on the blue box).

This is similar to undefined's answer but it doesn't abuse a real CSS property.

Note: The name of the custom property should be a jQuery.camelCase() name since .animate() uses the camelCased names internally and therefore, will store the current value of the property using the camelCased name and the fx.prop will also be the camelCased name.

Forget about jQuery's $.animate(), instead use $.velocity(). Velocity.js is an animation extention of jQuery. It uses the same syntax as jQuery and allows you to animate CSS3 such as 3D transforms, translates, rotates, colour fading, transitions, skews, ... Anything you want. And since it is smart enough to use CSS3 instead of JS where possible, it animates with a better performance aswell. I don't understand why jQuery doesn't do this yet!

http://julian.com/research/velocity/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!