如何使用Javascript创建带有精灵表的动画按钮

How can I create an Animated Button with a Sprite Sheet using Javascript?

本文关键字:动画 按钮 精灵 何使用 Javascript 创建      更新时间:2023-09-26

我正在尝试使用精灵表创建一个动画按钮。动画应该在悬停时播放,然后在鼠标悬停时播放。动画应该完成,然后停止。

我该怎么做?我尝试过设置div的背景,并通过悬停事件控制背景位置。我可以让背景位置正确设置,但每次更改都很快,可能是即时的,所以动画不会显示出来。

任何建议都会很有帮助。经过一番寻找,但没有运气,我不知道还能尝试什么。

谢谢!

最好的建议是使用CSS3。
非常简单,不需要javascript:

举个例子:

http://codeitdown.com/css-sprite-animations/

这里的示例:

http://jsfiddle.net/drukaman/ued7mLha/1/

来自裁判:https://medium.com/@Mrugraj/sprite-sheet-animation using-html-css-9091bebd4eeb

HTML

<html>
    <head>
        <title>
            Sprite-Sheet Animation
        </title>
        <link rel=”stylesheet” type=”text/css” href=”main.css”>
    </head>
    <body>
        <div class=”animatedDiv”></div>
    </body>
</html>

CSS

.animatedDiv {
    width: 820px;
    height: 312px;
    background-image: url("https://cf.dropboxstatic.com/static/images/index/animation-strips/hero-intro-bg-vflR5rUow.jpg");
    -webkit-animation: play 2s steps(48) infinite;
    -moz-animation: play 2s steps(48) infinite;
    -ms-animation: play 2s steps(48) infinite;
    -o-animation: play 2s steps(48) infinite;
    animation: play 2s steps(48) infinite;
}
@-webkit-keyframes play {
    from {
        background-position: 0px;
    }
    to {
        background-position: -39360px;
    }
}
@-moz-keyframes play {
    from {
        background-position: 0px;
    }
    to {
        background-position: -39360px;
    }
}
@-ms-keyframes play {
    from {
        background-position: 0px;
    }
    to {
        background-position: -39360px;
    }
}
@-o-keyframes play {
    from {
        background-position: 0px;
    }
    to {
        background-position: -39360px;
    }
}
@keyframes play {
    from {
        background-position: 0px;
    }
    to {
        background-position: -39360px;
    }
}

有关详细说明,请访问链接。