简体   繁体   中英

CSS3 keyframes - changing animation duration causes “jumps”

You can see what's happening here http://goo.gl/bBMx6x (it's a fiddle, it wouldn't allow me to post it without having to c&p code) click on start, wait a couple of seconds and then press stop.. it jumps to(I think) position where it would have been if it had lower duration from the beginning.

What I'm trying to do is have it spinning and then on stop "finish" the spin but a little faster..

That is not posible to do it the way that you are trying. (And for the reason that you guess)

You have to calculate in javascript the way the second animation has to begin.

webkit demo

The script is

$(document).ready(function() {
    $(".start").click(function(e) {
        e.preventDefault();
        var elem = document.getElementById('idtest');
        elem.style["-webkit-animation"] = "";
        elem.style["-webkit-animation-delay"] = "";

        $("#idtest").removeClass("spin2").addClass("spin");
    });

    $(".stop").click(function(e) {
        e.preventDefault();

        Stopping ();
    });

    $(".test").on("animationend",
        function() {
            $(this).removeClass("finishSpin");
        }
    );
});


function Stopping () {
    var elem = document.getElementById('idtest');
    var style = window.getComputedStyle (elem, null);
    var frame = style.getPropertyValue("z-index");
    var delay = - frame / 36;
    elem.style["-webkit-animation"] = "spin2 10s 1 linear";
    elem.style["-webkit-animation-delay"] = delay + "s";
    elem.className = "";
}

The idea is the following:

  1. When you press stop, get the computed style to know where in the animation the element is
  2. Since transforms are complicated to use, I also set the animation to change an easier value. In this case, I have choose z-index, but it can be whatever you want (that is not visible, of course)
  3. Use this value to set a negative delay on the new animation that you are setting. A negative delay is the way to make the transition begin mid-way.

I have adapted your fiddle only to webkit, but the idea would be the same for other browsers.

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