gpt4 book ai didi

javascript - 在红色和绿色之间切换标题的颜色

转载 作者:行者123 更新时间:2023-11-28 00:39:29 24 4
gpt4 key购买 nike

我写了一个代码,它是一个简单的代码,可以将 HTML 标题的颜色更改为红色,然后再更改为绿色,然后继续运行。但我的问题是关于定义变量“值”。因此,每次我在全局范围内定义变量值时,用于在红色和绿色之间切换颜色的循环工作,但是当我在我的启动函数中声明它时,循环不起作用它只是卡在绿色(即我的第一个实例)。有什么建议为什么它会这样吗??

问候,新编码员。

// first i decleared header value

header = document.querySelector('h1')


// after that i needed a toggel function to toggel the boolean values


function toggel(input)

{

output=!(input)

return output

}

// here if i comment var value out and put this inside the function start
it will just work for one instance and code will stop. And if put it outside like its down below, the LOOP will keep on going long toggling red to green and back to red

var value = toggel(true)


// after that i made a fucntion called "start" which will be called in
1000 miliseconds of interval and every time its called i toggel the value
of boolean value

function start()

{

function colorchanger()

{

// var value = toggel(value)

if (value == true)

{

return "red";

}

else

{

return "green";

}

}

out = colorchanger()

console.log(out)

header.style.color = out;

value = toggel(value)

}

setInterval("start()", 1000);

最佳答案

这么自以为是?

header = document.querySelector('h1');

setInterval(() => header.classList.toggle('onGreen') , 1000);
  h1 { 
color:red;
}
h1.onGreen {
color:green;
}
<h1>H1 "Header"</h1>

关于javascript - 在红色和绿色之间切换标题的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952974/

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