gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:03:26 25 4
gpt4 key购买 nike

我想隐藏并每隔一秒看到html中的一些元素。我在 JavaScript 中有这段代码。 hello() 从主 html 调用 onload。然后它用函数 go 调用来启动定时器!正如我所想的那样,它每一秒都会改变它显示的内容。

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;
}

}

最佳答案

通过将所有的if 语句(在第一个之后)设为else if 来对它们进行分组。这样, block 内的增量 (indexx+=1;) 不会导致下一个 if 为真。

关于javascript - 每隔一秒在 javascript 中显示和隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com