javaScript动画图像onmouseover / onmouseout

时间:2012-12-01 10:33:21

标签: javascript animation settimeout onmouseover onmouseout

我有一个门打开的动画(41帧),我想使用javaScript使它在onmouseover上打开,我希望它回到第1帧onmouseout。我不认为我在onmouseout部分做得很好。在此先感谢您的帮助!

HTML:
    <div onmouseover="startAnimation()" onmouseout="stopAnimation()" id="door2"></div>
    <div id="door">
    <img src="images/Animation_Door/0001.png">
    <img src="images/Animation_Door/0002.png">
    <img src="images/Animation_Door/0003.png">
    ...etc...(41 frames)

css:
    #door img{
    display: none;
    }

    #door img:first-child {
    display: block;
    }

javaScript:
    function startAnimation() { 
    var frames = document.getElementById("door").children;
    var frameCount = frames.length;

    for (i=0; i<41; i++) {
    setTimeout(function(){
    frames[i % frameCount].style.display = "none";
    frames[++i % frameCount].style.display = "block";
    }, 50*i);
    }
    }

    function stopAnimation() {
    var frames = document.getElementById("door").children;
    var frameCount = frames.length;

    for (i=0; i<1; i++){
    setTimeout(function(){
    frames[++i % frameCount].style.display = "none";
    frames[i % frameCount].style.display = "block";
    }, 50*i);
    }
    }

这是一个指向它的链接: http://www.reveriesrefined.com/test

1 个答案:

答案 0 :(得分:1)

我认为这可能更像你想要的东西:

var ti, frame = 0,
frames = document.getElementById('door').children;

function resetAnimation() {
    frame = 0;
    frames[0].style.display = 'block';
    for (var i = 1; i < frames.length; i++) {
        frames[i].style.display = 'none';
    }
}
function startAnimation() {
    console.log('start animation');
    resetAnimation();
    ti = setInterval(function() {
        frames[frame].style.display = 'none';
        frame ++;
        if (frame >= frames.length) frame = 0;
        frames[frame].style.display = 'block';
    }, 50);
}
function stopAnimation() {
    if (ti) {
        clearInterval(ti);
        ti = undefined;
    }
    resetAnimation();
}​

请注意,当您想要连续动画时,使用setInterval通常比使用setTimeout更合适。全局变量存储我们当前正在查看的帧。 resetAnimation将帧设置为零并相应地设置显示。 startAnimation设置一个间隔计时器,它隐藏旧帧,将帧增加1,并显示每50ms的新帧。停止动画只是清除间隔计时器并重置动画。