每隔一秒在javascript中显示和隐藏元素

时间:2013-05-15 16:44:01

标签: javascript html svg

我想隐藏,每隔一秒就会在html中看到一些元素。我在JavaScript中有这个代码。 hello()从主html调用onload。然后它启动计时器,并调用函数!因为我认为每一秒都会改变显示的内容。

function hello() {

myTimer();


}
var indexx = 0;
function myTimer(){
var myVar1=setInterval(function(){go1()},1000);
}
function go1()
{

 if(indexx==0)
    {
        var results = document.getElementById("water_2_5");
        results.setAttributeNS(null,"visibility","hidden");
        var results = document.getElementById("water_2_1");
        results.setAttributeNS(null,"visibility","visible");

        indexx+=1;

    }   else
    if(indexx==1)
    {
        results = document.getElementById("water_2_1");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_7");
        results.setAttributeNS(null,"visibility","visible");


        indexx+=1;

    }
    if(indexx==2)
    {
    results = document.getElementById("water_2_7");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_6");
        results.setAttributeNS(null,"visibility","visible");


        indexx+=1;

    }
    if(indexx==3)
    {
    results = document.getElementById("water_2_6");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_5");
        results.setAttributeNS(null,"visibility","visible");

                indexx=0;
        }

}

但它只向我显示,第一部分和最后一部分? 有人能帮助我如何实现这个目标吗?

回答是:

function hello() {

myTimer();


}
var indexx = 0;
function myTimer(){
var myVar1=setInterval(function(){go1()},1000);
}
function go1()
{

 if(indexx==0)
    {
        var results = document.getElementById("water_2_5");
        results.setAttributeNS(null,"visibility","hidden");
        var results = document.getElementById("water_2_1");
        results.setAttributeNS(null,"visibility","visible");

        indexx+=1;

    }   else
    if(indexx==1)
    {
        results = document.getElementById("water_2_1");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_7");
        results.setAttributeNS(null,"visibility","visible");


        indexx+=1;

    } else
    if(indexx==2)
    {
    results = document.getElementById("water_2_7");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_6");
        results.setAttributeNS(null,"visibility","visible");


        indexx+=1;

    }else 

    {
    results = document.getElementById("water_2_6");
        results.setAttributeNS(null,"visibility","hidden");
        //
        var results = document.getElementById("water_2_5");
        results.setAttributeNS(null,"visibility","visible");

                indexx=0;
        }

}

1 个答案:

答案 0 :(得分:3)

将所有if语句分组(在第一个之后)为else if。这样,块(indexx+=1;)内的增量不会导致下一个if为真。