我有一个程序应该在按下按钮时开始更改其背景颜色(这不是按钮,它是 <h1>
),但是当我按下它时,背景不会改变。它应该因为变量的变化而改变,但除此之外,我认为其余的都有效。
var onf = false;
setInterval(timer(), 100);
function startUp(){
document.getElementById("Temmie").textContent = "Hi";
turnOn();
}
function turnOn(){
document.getElementById("Tem").style.color = 'Chartreuse';
document.getElementById("Temmie").style.fontFamily = 'Papyrus';
document.getElementById("Temmie").style.fontSize = '24px';
onf = true;
}
function timer(){
if(onf == true){
t = Math.floor(Math.random() * 3) + 1;
changeBackground();
}
}
function changeBackground(){
if(t == 1){
document.body.style.background = 'ForestGreen';
}
if(t == 2){
document.body.style.background = 'DarkGreen';
}
if(t == 3){
document.body.style.background = 'SteelBlue';
}
}
“Tem”和“Temmie”标签连接到
和 ,但除此之外,这应该足够了。
最佳答案
你需要传递函数,而不是调用函数的结果。 timer
的返回值是undefined
,不是函数,也不是可执行代码。
setTimeout
获取一个函数(或字符串)并在给定时间间隔后调用它。
setInterval(timer, 100); // without ()
关于javascript - 我在 javascript 和 html 中有一个 true 或 false 变量的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899484/