Gajus
Gajus

Reputation: 73778

transitionless keyframes with CSS

In JavaScript, this could have been written as such:

var state = 0;
setTimeout(function keyFrames () {
    fooElement.style.backgroundPosition = '0 -' + (10*state++) + 'px';
    if (state === 2) {
        state = 0;
    }
    setTimeout(keyFrames, 500);
}, 500);

CSS3 keyframes offer a very similar functionality:

@keyframes foo { 0% { background-position: 0 0; } 50% { background-position: 0 -10px; } 100% { background-position: 0 -20px; } }
#fooElement { transition: foo 1500ms linear infinite; }

The difference is that CSS transition will utilise the timing function. Is there a way to replicate the exact JavaScript behaviour using CSS?

Upvotes: 4

Views: 244

Answers (1)

Martijn Hols
Martijn Hols

Reputation: 1613

You can achieve this using the animation timing function step-start or step-end. This will ensure there is no animation smoothing and each frame takes (total animation duration / frames), so in your case 500ms. An example of this working can be found here: http://jsfiddle.net/tUa6Y/3/ .

#fooElement { transition: foo 1500ms step-start infinite; }

See https://developer.mozilla.org/en-US/docs/CSS/timing-function for more information.

Edit: You might have to add a dummy frame to the start or end (depending on if you use step-start vs step-end) as the first or last frame seems to be given a duration of 0s.

Upvotes: 2

Related Questions