This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
                                
                                    (9个答案)
                                
                        
                                2年前关闭。
            
                    
我想通过单击课程来更改课程的背景颜色。我尝试的代码不起作用。先感谢您

HTML:

<a href="#!" onclick="message()" onclick="message()" class="changeBack"> SEND ME A MESSAGE </a>


CSS:

.changeBack {
    background-color: rgba(0, 0, 0, 0.0);
}


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)";
    }

}

最佳答案

有您的代码。



function myFunction() {
    var x = document.getElementById('box');
    if (x.style.backgroundColor === 'red') {
        x.style.backgroundColor = 'blue';
    } else {
        x.style.backgroundColor = 'red';
    }
}

#box{
background-color:red;
padding:1rem;
width : 50%;
height:150px;
margin:auto;
}

<div id="box" onclick="myFunction()">
</div>

关于html - 使用onclick函数更改背景颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42427377/

10-12 12:25