隐藏/显示Div元素

时间:2011-10-05 18:31:19

标签: javascript html css

这应循环显示<div>标签,但它甚至不显示第一个标签。它应显示“0”,然后50ms后显示“1”,然后显示“2”,然后显示“3”。我一无所获。

这是HTML:

<div class="header" id="animation">
<div id="aniObj0" style="display: none;" onLoad="runAnimation();">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>

JavaScript:

var aniNum = 0;
var animationDelay = 50;
var frameDelay = 50;

function runAnimation()
{
    Console.log("runningAnimation");
    var prevObj = document.getElementById('aniObj' + (aniNum - 1));
    var aniObj = document.getElementById('aniObj' + aniNum);
    if(aniObj != null){
        if(prevObj != null){
            aniObj.style.display = 'none;';
        }
        aniObj.style.display = 'block;';
        aniNum++;
        if(aniNum == 0){
            setTimeout("runAnimation();", animationDelay);
        }else{
            setTimeout("runAnimation();", frameDelay);
        }
    }else{
        aniNum = 0;
        newAnimation();
    }
}

1 个答案:

答案 0 :(得分:3)

你非常接近。请参阅下面的代码(以及代码中的注释)。

<强> HTML:

<div class="header" id="animation">
    <!-- Removed onload="runAnimation()" - onload doesn't exist for a div -->
    <div id="aniObj0" style="display: none;">0</div>
    <div id="aniObj1" style="display: none;">1</div>
    <div id="aniObj2" style="display: none;">2</div>
    <div id="aniObj3" style="display: none;">3</div>
</div>

<强> JavaScript的:

var aniNum = 0;
var animationDelay = 500; //Changed to 500ms to you could see better
var frameDelay = 500; //Changed to 500ms to you could see better

function runAnimation()
{
    var prevObj = document.getElementById('aniObj' + (aniNum - 1));
    var aniObj = document.getElementById('aniObj' + aniNum);

    if (aniObj != null) {
        if (prevObj != null) {
            aniObj.style.display = 'none;';
        }
        aniObj.style.display = '';
        aniNum++;
        if (aniNum == 0) {
            //Changed setTimeout("runAnimation()", animationDelay); to 
            //setTimeout(runAnimation, animationDelay);
            setTimeout(runAnimation, animationDelay);
        } else {
            setTimeout(runAnimation, frameDelay);
        }
    } else {
        aniNum = 0;
        newAnimation();
    }
}

//You need to place this in a valid event. onload event of the body maybe?
runAnimation();

这是a working fiddle