我希望制作一个执行 JavaScript 函数来更改背景颜色的 html 按钮。
这是我的代码:
<button onclick = "backgroundChange()">Press Me</button>
document.body.style.backgroundColor = "white";
function backgroundChange () {
if (document.body.style.backgroundColor = "white") {
document.body.style.backgroundColor = "red";
}
else if (document.body.style.backgroundColor = "red") {
document.body.style.backgroundColor = "white";
}
}
我做错了什么, children ?
最佳答案
使用相等(==
)而不是赋值(=
)operator.document进行正确的比较。
document.body.style.backgroundColor = "white";
var btn = document.querySelector('button');//it selects your button element you can also select using id,class,..
btn.onclick = function() //handles the click event
{
if (document.body.style.backgroundColor == "white") {
document.body.style.backgroundColor = "red";
}
else if(document.body.style.backgroundColor == "red") {
document.body.style.backgroundColor = "white";
}
}
<button onclick = "backgroundChange()">Press Me</button>
关于javascript - 具有 JavaScript 功能的 HTML 按钮可更改 BG 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42991142/