我给你留下了一个粗糙的example http://jsbin.com/otelu这样你就可以得到一个起点:
我将使用一个简单的 div 元素,width
and height
动画图像将具有 png 精灵为background-image
and background-repeat
set to no-repeat
需要CSS:
#anim {
width: 14px; height: 14px;
background-image: url(https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/wink2.png);
background-repeat: no-repeat;
}
需要标记:
<div id="anim"></div>
技巧基本上是向上滚动背景图像精灵,使用background-position
CSS 属性。
我们需要知道height
动画图像的大小(了解我们每次向上滚动多少)以及滚动多少次(多少次)frames会有动画)。
JavaScript 实现:
var scrollUp = (function () {
var timerId; // stored timer in case you want to use clearInterval later
return function (height, times, element) {
var i = 0; // a simple counter
timerId = setInterval(function () {
if (i > times) // if the last frame is reached, set counter to zero
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up
i++;
}, 100); // every 100 milliseconds
};
})();
// start animation:
scrollUp(14, 42, document.getElementById('anim'))
EDIT:您还可以以编程方式设置 CSS 属性,这样您就不必在页面上定义任何样式,并创建一个构造函数 https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function从上面的示例来看,这将允许您同时显示多个精灵动画:
Usage:
var wink = new SpriteAnim({
width: 14,
height: 14,
frames: 42,
sprite: "https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/wink2.png",
elementId : "anim1"
});
var monkey = new SpriteAnim({
width: 18,
height: 14,
frames: 90,
sprite: "https://ssl.gstatic.com/ui/v1/icons/mail/im/emotisprites/monkey1.png",
elementId : "anim4"
});
执行:
function SpriteAnim (options) {
var timerId, i = 0,
element = document.getElementById(options.elementId);
element.style.width = options.width + "px";
element.style.height = options.height + "px";
element.style.backgroundRepeat = "no-repeat";
element.style.backgroundImage = "url(" + options.sprite + ")";
timerId = setInterval(function () {
if (i >= options.frames) {
i = 0;
}
element.style.backgroundPosition = "0px -" + i * options.height + "px";
i++;
}, 100);
this.stopAnimation = function () {
clearInterval(timerId);
};
}
请注意,我添加了一个stopAnimation
方法,这样您以后就可以通过调用它来停止指定的动画,例如:
monkey.stopAnimation();
检查上面的例子here http://jsbin.com/ifaci.