Can I set the progress of a keyframe animation to a specific stage?

孤者浪人 提交于 2019-12-21 07:19:10

问题


I have a keyframe animation with multiple steps:

@keyframes rotateLeftSideCustom {
    0% {
    }
    40% {
        -webkit-transform: rotateY(-15deg);
        transform: rotateY(-15deg);
        opacity: .8;
        -webkit-animation-timing-function: ease-out;
        animation-timing-function: ease-out;
    }
    100% {
        -webkit-transform: scale(0.8) translateZ(-200px);
        transform: scale(0.8) translateZ(-200px);
        opacity: 0;
    }
}

.section-animation {
    -webkit-transform-origin: 100% 50%;
    transform-origin: 100% 50%;
    -webkit-animation: rotateLeftSideCustom 0.6s both ease-in;
    animation: rotateLeftSideCustom 0.6s both ease-in;
}

Is there any way I can use JavaScript to set the progress of the animation?

Eg:

document.querySelector('.section-animation').animationState('40%');

Context: I'm trying to build a draggable interface where I need to align the progress of the animation with the amount of dragging the user does.


回答1:


Did I get it right, that you want to start the the animation not at 0%, but at 40%?

There's a way to do it CSS-only, by using negative value for animation-delay

.section-animation {
    animation-delay: -0.24s; /*40% of 0.6s */
}

Additionally, you might want to add

.section-animation {
    animation-play-state: paused;
}

to your element, so that you might can see the state of the animation as a static image, not animated.

Here's a link: https://css-tricks.com/starting-css-animations-mid-way/




回答2:


You could use jQuery for animation. With .animate() you have a property step.

animate API

From the docs:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>animate demo</title>
  <style>
  div {
    position: relative;
    background-color: #abc;
    width: 40px;
    height: 40px;
    float: left;
    margin: 5px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><button id="go">Run »</button></p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>

<script>
$( "#go" ).click(function() {
  $( ".block:first" ).animate({
    left: 100
  }, {
    duration: 1000,
    step: function( now, fx ){
      $( ".block:gt(0)" ).css( "left", now );
    }
  });
});
</script>

</body>
</html>

Where *now* is the actual state of your animation.

UPDATE

Propably you can use requestAnimationFrame but this is also like my other solution. The difference is - that it's pure JavaScript, so no external library needed.



来源:https://stackoverflow.com/questions/29774433/can-i-set-the-progress-of-a-keyframe-animation-to-a-specific-stage

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