Вопрос

I'm trying to make an animation using a PNG sequence, which has a transition on hover, and animates back when the hover state ends.

For this I'm using a css transition with a "steps" timing function, like so:

transition:background .5s steps(9, end);

See the fiddle for a live example (I've used a random PNG sprite that I Googled, it's not the one I'm actually using)

http://jsfiddle.net/MLWL5/

Basically this is working fine, when you hover over the element slowly. When you quickly hover on and off the element, the transition seems to trigger when the background image if halfway through the previous transition, and then the number of steps don't match which will get an undesired effect.

I could use javascript to trigger the transition, but does anyone know if there's a CSS only solution for this?

Это было полезно?

Решение

It's not a perfect solution, but you can have it somehow working handling the hover change with an animation instead.

It will work ok if you un-hover after the animation has finished, but it won't animate at all if you un-hover quickly

CSS

div { width:50px; 
    height:72px;             background:url(http://openbookproject.net/thinkcs/python/english3e/_images/duke_spritesheet.png) left top;
    transition:background 1.5s steps(9, end);
    background-position: 0px top; 
    -webkit-animation: none;
}

div:hover { 
    background-position:-450px top; 
    -webkit-animation: bkg 1.5s steps(9);
    transition: none;

} 

@-webkit-keyframes bkg {
    0% {background-position: 0px top;}
  100% {background-position: -450px top;}
}

CSS demo

And, a solution using jQuery. This one rewinds the animation from the point where it was at the un-hover moment. It also recalculates the time, so that it doesn't slow down

jQuery

$( "div" ).hover(
    function() {
        var elem = $(this);
        var cur = parseInt(elem.css("background-position-x"));
        var steps = (450 + cur) / 50;
        var time = steps * 0.1;
        var trans = "background " + time + "s steps(" + steps + ", end)";
        elem.css("transition", trans);
        elem.css("background-position", "-450px 0px");
    }, 
    function() {
        var elem = $(this);
        var cur = parseInt(elem.css("background-position-x"));
        var steps = - cur / 50;
        var time = steps * 0.1;
        var trans = "background " + time + "s steps(" + steps + ", end)";
        elem.css("transition", trans);
        elem.css("background-position", "0px 0px");
  }
);

jQuery demo

The jQuery code can be streamlined a little, using functions to avoid duplicate code, but I have set it to be as clear as posible

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top