CSS transition on png sequence using steps

拈花ヽ惹草 提交于 2019-12-05 19:51:50

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

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