使用 javascript 暂停 CSS 动画并跳转到动画中的特定位置

问题描述:

我有一个完全用 CSS 动画构建的无尽滑块,我希望能够使用 javascript(onlcick 和键盘输入)操纵动画.我希望能够从一帧快速运行动画,即加速它......到另一帧以在按下指向滑块中特定图像的按钮时产生跳跃效果.另外,我希望能够通过键盘输入逐步完成动画...( --> , <-- )

I have an endless slider built entirely with CSS animations and I want to be able to manipulate the animation with javascript (onlcick and keyboard input). I want to be able to run through the animation rapidly from one frame, ie, speeding it up.. to another to give a jumping effect when a button is pressed that refers to a specific image in the slider. Also, I want to be able to step through the animation with keyboard input... ( --> , <-- )

有人知道如何实现吗?

点击...

  1. 检索当前关键帧位置;
  2. 为目的地设置适当的方向;
  3. 大幅提高动画速度,直到达到所需的关键帧;
  4. 暂停动画或从新点继续

键盘输入...

  1. 跳转到特定的关键帧并继续动画

尝试

html

<!-- html -->
<div id=animated></div>

CSS

      /* css */

    #animated {

      animation : animationName; /* animation block(s) */

      animation-play-state : paused; /* (paused; running) */ 

    }

    @keyframes animationName {

      0% { .. /* css animations (`animationstart`) */ }

      50% {..}

      100% { .. /* css animations (`animationend` / `animationiteration` (start; end)) */ }

    }

js

 (function(el) {

   function animations(e) {

     /* `key code` to trigger event */
     if (e.which === 123456) {

       $(el).animate({ /* jquery animations */ }, 123456 /* duration */)
       .promise().done(function() {
         el.style.animationPlayState = "running";
         el.style.WebkitAnimationPlayState = "running";
        });

      };

    };

$(window).on("keydown", animations);
})($(#animated).get(0))

$(document).ready(function() {

    (function reanimate(el, r, p, runner, pauser, pauseAll) {

        var _state = function() {
            $.when(
            $("#animated").data("states", {"fxq": "animated!","cssAnimationState": (el.style.WebkitAnimationPlayState || el.style.animationPlayState),"jsAnimationState": $("#animated").queue("fx")[0]}))
            .done(function(status) {
                return status.data("states")
            });

            return String("css animation state: " + (el.style.WebkitAnimationPlayState || el.style.animationPlayState) + "&nbsp; js animation state: " + $("#animated").queue("fx")[0])
        };

        var runner = function() {
            el.style.animationPlayState = "running";
            el.style.WebkitAnimationPlayState = "running";
            return $("data").html(_state())
        };

        var pauser = function() {
            el.style.animationPlayState = "paused";
            el.style.WebkitAnimationPlayState = "paused";
            $("#animated:animated, #animated *").finish().queue("fx", []);
            return $("data").html(_state())

        };

        $("button:last").on("click", pauser);
        $("button:first").on("click", runner);

        function player(e, pause, play, pauseAll) {

            /*!
            //  settings
            */
            var pauseAll = (undefined || 38); /* `up-arrow` : `pauseAll` */
            var pause = (undefined || 37); /* `left-arrow` : `paused` */
            var play = (undefined || 39); /* `right-arrow` : `running` */

            if (e.which === play) {
                e.preventDefault();
                runner();
                $("data").html(_state())
            };
            /*!
            //  js (jquery) animations (, css transitions,
            //  css animations) at `paused` css animations
            */
            if (e.which === pause) {
                e.preventDefault();
                $.when(
                $('#animated')
                .animate({
                    width: "+=400px",
                    height: "+=400px",
                    borderRadius: "+=50%",
                    fontSize: "+=22px"
                },
                {
                    duration: 3500,
                    easing: "swing",
                    start: $('#animated').css({"transition": "background 3500ms linear, box-shadow 3500ms linear","-webkit-transition": "background 3500ms linear, -webkit-box-shadow 3500ms linear","-moz-transition": "background 3500ms linear, -moz-box-shadow 3500ms linear","background": "yellow","box-shadow": "0.25em 0.25em 0.25em #f57900","-webkit-transform-style": "preserve-3d","-webkit-transform": "rotateX(180deg) rotateZ(45deg)","-moz-transform-style": "preserve-3d","-transform": "rotateX(180deg) rotateZ(45deg)","-webkit-backface-visibility": "visible","-moz-backface-visibility": "visible"}).html(function() {
                        return $("<em>" + $('#animated').data("states").fxq + "</em>").css({"display": "block","position": "relative","top": "25%","left": "0%","transform": "rototeX(33deg)","text-shadow": "2px 2px 2px orange"}).fadeIn(2000, function() {
                            _state()
                        })
                    })
                })
                .animate({width: "100px",height: "100px",
                    borderTopLeftRadius: "0%",
                    borderTopRightRadius: "0%",
                    borderBottomLeftRadius: "0%",
                    borderBottomRightRadius: "0%",
                    fontSize: "10px"}, {
                    duration: 3500,
                    easing: "linear",
                    done: function() {
                        $('#animated').css({"transition": "background 3500ms ease-out, box-shadow 2500ms ease-out","-webkit-transition": "background 3500ms, -webkit-box-shadow 3500ms ease-out","-moz-transition": "background 3500ms ease-out, -moz-box-shadow 3500ms ease-out","background": "red","box-shadow": "0.0em 0.0em 0.0em transparent","-webkit-transform": "rotateX(0deg) rotateY(0deg) rotateZ(0deg)","transform": "rotateX(0deg) rotateY(0deg) rotateZ(0deg)","-moz-backface-visibility": "hidden","-webkit-backface-visibility": "hidden"}).children("em").fadeOut(2000, function() {
                            _state()
                        }).promise().done(function() {
                            $("em").finish().detach()
                        })
                    }
                }), $("data").html(_state())).promise().done(function() {
                    runner();
                }).always(function() {_state()})
            };
            /*!
            //  pause all css and js animations
            */
            if (e.which === pauseAll) {
                e.preventDefault();
                (function() {
                    var _check = ($("#animated").queue("fx")[0] != undefined ? $("#animated:animated, #animated *").finish() && pauser() : ((el.style.animationPlayState === undefined ? el.style.WebkitAnimationPlayState : el.style.animationPlayState) === "running" ? pauser() : runner()))

                    return $.when(_check, $("data").html(_state()))

                }())
            };
        };
        $(window).on("keydown", player);

        return $("data").html(_state())
    })($("#animated").get(0), "running", "paused")
})

http://guest271314.github.io/reanimate/

可能有几种可能的方法来完成要求,包括 CSSOM、Javascript、jQuery 库.查看链接.

There may be several possible ways to accomplish the requirement, including CSSOM, Javascript, jQuery library. See links.

开始和暂停 css 动画可以通过animation-play-state 属性.

Starting and pausing css animations can be done through the animation-play-state property.

可以通过多种方式启动和停止 jquery 动画.$(element).queue("fx", []) 应该停止所有 jquery 动画并清除jquery 动画 queue..finish() 应该完成,或者 finish 当前运行或 inprogress jquery 动画.

Starting and stopping jquery animations can be done a couple ways. $(element).queue("fx", []) should stop all jquery animations and clear jquery animations queue. .finish() should complete, or finish the currently running, or inprogress jquery animations.

animation-play-state : paused不会停止 jquery 动画.

animation-play-state : paused will not stop jquery animations.

这个过程也可以通过插入、替换、或删除 style 元素,或仅删除 style 元素中的文本;animationstartanimationiteration DOM 事件;和其他一些潜力选项链接如下.

The process could also be accomplished by inserting, replacing, or removing style element(s), or only text within the style element; animationstart, and animationiteration DOM events; and some other potential options linked below.

将 reanimate.js 放在一起,包括几个上面提到的方法.包含 css 转换在 jquery 动画中,虽然那部分可能被替换为访问准确的计时阶段运行 css 动画(@keyframes"),和/或插入新动画;或调整或重新定义时间.

Put the piece reanimate.js together including a couple of the above mentioned methods. css transitions were included within the jquery animations, though that portion could probably be substituted for either accessing the exact timing phase of the running css animation ("@keyframes"), and/or inserting new animations; or adjusting, or redefining timings.

这篇文章只是一个工作草案模板,用于共享预测功能.请注意,webkit、firefox 和opera 可能会以稍微不同的方式渲染"动画.使用这个模板 webkit 可能看起来过渡"更平滑"比 Firefox 更运行"的 css 动画.完整的歌剧支持可能需要一些更多微调.

This piece is just a working draft template to share prosepctive functionality. Note, webkit, firefox and opera may "render" the animations slightly differently. Using this template webkit may appear to "transition" somewhat more "smoother" to a "running" css animation than firefox. Full opera support may require some more fine tuning.

Opera 似乎对某些 css 属性使用 -o--webkit- 前缀,而其他人仅使用 w3c 标准(无前缀).此外,每个浏览器可能需要不同的前缀"来访问animationstart"等

Opera appears to use -o-, and -webkit- prefixes for some css properties, while using only w3c standards (no prefixes) for others. Also, each browser may require a different "prefix" for accessing "animationstart", etc.

reanimate.js 当前(1.0 版)不会尝试访问确切的 csskeyframe '(elapsedTime) 在 running css 动画内/在中断前它们具有多个 layered 或重新动画化"的 css/js 动画和/或 css 转换.而是尝试将 css 动画返回到大致位置他们在分层"js动画中断之前运行.虽然,它应该可以访问精确的动画 elapsedTimetimeStamp(可能是 0 或 miiliseond 类型的时间戳,取决于浏览器)关键帧.例如,通过访问animationiteration"或animationstart"或animationend"事件,或者可能使用requestAnimationFrame".

reanimate.js does not currently (version 1.0) attempt to access the exact css keyframe '(elapsedTime) within/of the running css animation before interrupting them with several layered or "reanimated" css/js animations an/or css transitions. But rather, attempts to return the css animation(s) to the approximate position which they were running at before the "layered" js animation interruption. Though, it should be possible to access that exact animation elapsedTime or timeStamp (which may be 0 or a miiliseond-type time stamp, depending on the browser) of the keyframes. For example, by accssing the "animationiteration" or "animationstart" or "animationend" events, or by possible usage of "requestAnimationFrame".

资源:

以编程方式更改动画规则中的 webkit-transformation 值

使用 Javascript 变量设置 Webkit 关键帧值位置http://jsfiddle.net/russelluresti/RHhBz/2/

更改或生成并删除 css3 关键帧一个>

使用 Javascript 更改 css 中的不同关键帧

https://developer.apple.com/library/safari/documentation/AudioVideo/Reference/WebKitAnimationEventClassReference/WebKitAnimationEvent/WebKitAnimationEvent.html

http://msdn.microsoft.com/en-us/library/ie/hh772074%28v=vs.85%29.aspx

http://blogs.msdn.com/b/msdn_answers/archive/2013/11/04/part-i-using-javascript-to-set-keyframes-in-css-animations-windows-store-apps-ie.aspx

http://www.w3.org/TR/animation-timing/一个>

希望能帮到你