2017-02-23 259 views
0

我想通过单击类来更改类的背景颜色。我试过的代码不起作用。谢谢你在前进使用onclick-function更改背景颜色

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

} 

回答

1

还有就是你的代码。

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>

+0

它不会在我的档案工作。我已经有了另一个onclick函数(请参阅编辑),或者这是不可能的?它必须包含一个if/else语句,因为每次单击该类时都会更改。编辑:我删除了消息(),然后它确实有效,但是如果我将它们结合在一起,它不会。 – Soccerlife

+0

它现在工作谢谢你! – Soccerlife

+0

我编辑我的代码片段以便切换脚本,现在可以运行它,它每次都在变化。 – Nadim