javascript - 具有 JavaScript 功能的 HTML 按钮可更改 BG 颜色

标签 javascript html

我希望制作一个执行 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/

相关文章:

javascript - 防止透明div内的图像透明

html - 图像边框悬停不起作用

javascript - wordpress 和 wp_query 中的 ajax

javascript - 数据表子行形式

javascript - 如何正确使用多个初始化函数?

javascript - HTML5输入类型="file"不会触发handleFileSelect()

javascript - 如何获取 ID 集合以及从 View 表传递到 Controller 的选定下拉列表值?

javascript - 如何获取 Jquery Datatable 中字符串格式的选定值

javascript - 正则表达式 英国邮政编码 Javascript 空间问题

html - 自动调用电话号码