简体   繁体   中英

Rotate div after animation

I'm trying to create a sort of crash test dummy, when you click in the document window my .person div will move right and then at the end animate tilt forward, and then tilt back to its original place.

I've got the css for the transform working, only its tilting my div immediately and not at the end of the movement? sorry if this is hard to understand, I've created a jsFiddle to explain...

http://jsfiddle.net/4mzg8/3/

// On click my .person div will move right, once moved it needs to tilt forward and then backwards - as though its hit a wall...

$(document).on('click',function(){
    $('.person').animate({ "left": "+=250px" }, 500, crashImpact(30));
});

function crashImpact(tilt) {
    $('.person').css({
        transform: 'rotate(' + tilt + 'deg)'
    });
}

It needs a little work, but you can do the whole thing in CSS just by adding a class and chaining animations...

Demo Fiddle - (Chrome)

JS

$(document).on('click', function () {
    $('.person').addClass('go');
});

CSS

.person.go {
    -webkit-animation-delay:0, .5s;
    -webkit-animation-duration:.5s, .5s;
    -webkit-animation-iteration-count:1, 1;
    -webkit-animation-name:animForward, animTilt;
    -webkit-animation-timing-function:ease-in;
    -webkit-animation-fill-mode:forwards;
    -webkit-transform-origin: 0%;
}
@-webkit-keyframes animForward {
    from {
        margin-left: 0;
    }
    to {
        margin-left: 400px;
    }
}
@-webkit-keyframes animTilt {
    0% {
        -webkit-transform:rotate(0deg);
    }
    50% {
        -webkit-transform:rotate(45deg);
    }
    100% {
        -webkit-transform:rotate(0deg);
    }
}
$(document).on('click',function(){
    $('.person').animate({ "left": "+=250px" },500,function(){
        crashImpact(30);
    });
});

function crashImpact(tilt) {
    $('.person').css({
        'transform': 'rotate(' + tilt + 'deg)'
    });
}

I modified your code. Check here : http://jsfiddle.net/lotusgodkk/4mzg8/4/

You have written:

$('.person').animate({ "left": "+=250px" }, 500, crashImpact(30));

This will call crashImpact function immediately.

Change it to:

$('.person').animate({ "left": "+=250px" },500,function(){
    crashImpact(30);
});

This will call crashImpact function after execution of animate is completed.

transition property will rotate .person smoothly.

Write:

CSS:

.transform{
    transition:all 1s;
    -webkit-transition:all 1s;
}

JS:

function crashImpact(tilt) {
    $('.person').css({
        'transform': 'rotate(' + tilt + 'deg)'
    }).addClass("transform");
}

Updated fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM