问题
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