How to make a CSS animation/transition play at a fixed speed, not a fixed duration? [duplicate]

我只是一个虾纸丫 提交于 2020-06-27 03:57:10

问题


I have a CSS animation that makes an element move an undefined distance in a straight line. Animations have fixed durations, as far as I know, so the animation always takes the same amount of time to run, no matter how far the element has to move.

How do I make it so the animation doesn't have a fixed duration, but a fixed movement speed? I want something like "X pixels movement per second" instead of "X seconds for the whole animation." My animation will be used on several elements that move different distances, and I don't want to make separate animations for each one.

Can this be achieved only with CSS?


回答1:


function move(id,x) {
  document.getElementById(id).style.transitionDuration = (x/200) + 's';
  document.getElementById(id).style.marginLeft = x + 'px';
}
#a,#b {
  width: 50px;
  height: 50px;
  margin-left: 10px;
  transition-timing-function: linear;
}

#a {
  background-color: red;
}

#b {
  background-color: blue;
}
<div id='a' onclick="move('a',400)"></div>
<div id='b' onclick="move('b',250)"></div>
<button onclick="move('a',400);move('b',250)">Or click here!</button>

The transition-timing-function: linear allows you to make the transition happen in a linear fashion, rather than speeding up and slowing down on the ends. Also, I was unable to find a pure CSS solution, but one line of JavaScript can create the desired effect.



来源:https://stackoverflow.com/questions/39713882/how-to-make-a-css-animation-transition-play-at-a-fixed-speed-not-a-fixed-durati

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