How to change a property in a CSS animation abruptly without animating

馋奶兔 提交于 2019-12-11 06:43:53

问题


Here is what I am trying to figure out, but without using the 51% keyframe as a hacky way to implement the change of transform-origin. Here is a Fiddle Demo.

@keyframes spin {
  0% { 
    transform-origin: 50% 0; 
    transform: perspective(800px) rotateX(0deg) translateZ(0px); 
  }
  50% { 
    transform-origin: 50% 0; 
    transform: perspective(800px) rotateX(360deg) translateZ(0px); 
  } 
  51% { 
    transform-origin: 50% 100%; /* hacky way to instantly change transform-origin */ 
  }
  100% {
    transform-origin: 50% 100%; 
    transform: perspective(800px) rotateX(0deg) translateZ(0px); 
  } 
} 

回答1:


As I had mentioned in my comment, there is no way to achieve this with just a single animation. I wouldn't call your original approach as hacky because a sudden change means the addition of a new keyframe immediately after the previous one (50% and 51%) but I kind of get what you mean to say.

One possible alternate is to make use of two animations - one for the transform and the other for the transform-origin change. Here we can make the second animation (the transform-origin change) alone have a steps (or step-end) timing function so that this change alone happens abruptly.

(Note: I'm providing this option just as an answer to your question. I'd still prefer the earlier approach and avoid having two different keyframe rules to perform the same animation.)

Below is a sample snippet:

.image {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 120px;
  height: 120px;
  margin: -60px 0 0 -60px;
  animation: spin 4s linear infinite, origin 4s step-end infinite;
  transform-origin: 50% 0;
}
@keyframes spin {
  0% {
    transform: perspective(800px) rotateX(0deg) translateZ(0px);
  }
  50% {
    transform: perspective(800px) rotateX(360deg) translateZ(0px);
  }
  100% {
    transform: perspective(800px) rotateX(0deg) translateZ(0px);
  }
}
@keyframes origin {
  50% {
    transform-origin: 50% 100%;
  }
}
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">


来源:https://stackoverflow.com/questions/41801802/how-to-change-a-property-in-a-css-animation-abruptly-without-animating

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