Html 使用onclick功能更改背景色

Html 使用onclick功能更改背景色,html,css,onclick,Html,Css,Onclick,我想通过单击类来更改类的背景色。我试过的代码不起作用。先谢谢你 HTML: JAVASCRIPT: function message() { var background = document.getElementsByClassName("changeBack").style.backgroundColor; if (background == "rgba(0, 0, 0, 0.0)") { background =

我想通过单击类来更改类的背景色。我试过的代码不起作用。先谢谢你

HTML:

JAVASCRIPT:

function message() {

        var background = document.getElementsByClassName("changeBack").style.backgroundColor;
            if (background == "rgba(0, 0, 0, 0.0)") {
                 background = "rgba(0, 0, 0, 0.1)";
        } else {
        background = "rgba(0, 0, 0, 0.0)";
    }

}
这是你的密码

函数myFunction(){
var x=document.getElementById('box');
如果(x.style.backgroundColor=='red'){
x、 style.backgroundColor='蓝色';
}否则{
x、 style.backgroundColor='红色';
}
}
#框{
背景色:红色;
填充:1rem;
宽度:50%;
高度:150像素;
保证金:自动;
}

这是您的代码

函数myFunction(){
var x=document.getElementById('box');
如果(x.style.backgroundColor=='red'){
x、 style.backgroundColor='蓝色';
}否则{
x、 style.backgroundColor='红色';
}
}
#框{
背景色:红色;
填充:1rem;
宽度:50%;
高度:150像素;
保证金:自动;
}


它在我的文件中不起作用。我已经有了另一个onclick函数(参见编辑),或者这是不可能的?它必须包含if/else语句,因为每次单击该类时它都在更改。编辑:我删除了邮件(),然后它就可以工作了,但是如果我将它们组合在一起,它就不能工作了。现在可以工作了,谢谢!我将代码段编辑为切换脚本,您现在可以运行它,它每次都在更改。它在我的文件中不起作用。我已经有了另一个onclick函数(参见编辑),或者这是不可能的?它必须包含if/else语句,因为每次单击该类时它都在更改。编辑:我删除了邮件(),然后它就可以工作了,但是如果我将它们组合在一起,它就不能工作了。现在可以工作了,谢谢!我将我的代码片段编辑为切换脚本,现在您可以运行它,它每次都在更改。
.changeBack {
    background-color: rgba(0, 0, 0, 0.0);
}
function message() {

        var background = document.getElementsByClassName("changeBack").style.backgroundColor;
            if (background == "rgba(0, 0, 0, 0.0)") {
                 background = "rgba(0, 0, 0, 0.1)";
        } else {
        background = "rgba(0, 0, 0, 0.0)";
    }

}