4

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?

1
  • 1
    Do you menans 500ms jumps between states? @keyframes foo { 0% { background-position: 0 0; } 49% { background-position: 0 0; } 50% { background-position: 0 -10px; } 99%{ background-position: 0 -10px;} 100% { background-position: 0 -20px; } } Commented Dec 21, 2012 at 14:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.