我正在尝试使用setTimeout更改javascript中某些按钮的颜色。下面的代码中似乎有多个样式元素的问题?
有什么想法可以修复下面的代码吗?或者有更好的方法让柜台正常工作?
这是按钮样式等:
<button type="playball1" style="border-radius: 12px" style="border-radius: 50%";onclick = "null">1</button>
function changeButtonColor1() {
document.getElementById("playball1").style.backgroundColor = "green";
}
function changeButtonColor2() {
document.getElementById("playball2").style.backgroundColor = "green";
}
function changeButtonColor3() {
document.getElementById("playball3").style.backgroundColor = "green";
}
function changeButtonColor4() {
document.getElementById("playball4").style.backgroundColor = "green";
}
function changeButtonColor5() {
document.getElementById("playball1").style.backgroundColor = "green";
}
function Playball() {
setTimeout('changeButtonColor1()',1000);
setTimeout('changeButtonColor2()',2000);
setTimeout('changeButtonColor3()',3000);
setTimeout('changeButtonColor4()',4000);
setTimeout('changeButtonColor5()',1000);
};
发布于 2020-01-13 06:32:55
您的代码不起作用,因为您试图用getElementById("playball1")
获取元素,而您设置了他的类型type="playball1"
,而您应该使用id="playball1"
。
我不理解你的需求,但我认为你想要这样的东西:
function changeButtonColor(id) {
document.getElementById(id).style.backgroundColor = "green";
}
function playball() {
setTimeout('changeButtonColor("playball1")',1000);
setTimeout('changeButtonColor("playball2")',2000);
setTimeout('changeButtonColor("playball3")',3000);
setTimeout('changeButtonColor("playball4")',4000);
setTimeout('changeButtonColor("playball5")',5000);
};
playball();
<button id="playball1" style="border-radius: 12px" style="border-radius: 50%" onclick="null">1</button>
<button id="playball2" style="border-radius: 12px" style="border-radius: 50%" onclick="null">2</button>
<button id="playball3" style="border-radius: 12px" style="border-radius: 50%" onclick="null">3</button>
<button id="playball4" style="border-radius: 12px" style="border-radius: 50%" onclick="null">4</button>
<button id="playball5" style="border-radius: 12px" style="border-radius: 50%" onclick="null">5</button>
发布于 2020-01-13 06:27:59
您的函数不会被调用,并且还会尝试使用一个函数来管理您的代码,因为它们都在做相同的工作,请检查此示例
const playball1 = document.getElementById('playball1');
const playball1 = document.getElementById('playball2');
let green ='green';
let red = 'red';
function changeButtonColor1(element, color) {
element.style.backgroundColor = color;
}
changeButtonColor1(playball1,green );
changeButtonColor1(playball2,red);
https://stackoverflow.com/questions/59708328
复制相似问题