单击时更改按钮的颜色

时间:2017-04-11 04:31:12

标签: javascript

我有两个用户可以点击的按钮。目标是让用户能够点击按钮并让它改变我已经完成的颜色。但问题是我希望当他们点击另一个按钮时颜色会恢复原来的颜色,反之亦然。这是我的代码。

<div id='rightAlign'>
    <div id="but1">
        <button id="button1">Click Me</button>
        <button id="button2">Click Me</button>
    </div>
</div>


<script>
    var button1 = document.getElementById("button1");
    var button2 = document.getElementById("button2");

    button1.addEventListener("click", function() {
        button1.style.backgroundColor = "red";

        button2.addEventListener("click", function() {
            button2.style.backgroundColor = "red";


        });

3 个答案:

答案 0 :(得分:0)

您需要重置其他var button1 = document.getElementById("button1"); var button2 = document.getElementById("button2"); var button1Default, button2Default; button1Default = button1.style.backgroundColor; button2Default = button2.style.backgroundColor; button1.addEventListener("click", function(){ button1.style.backgroundColor = "red"; button2.style.backgroundColor = button2Default; }); button2.addEventListener("click", function(){ button2.style.backgroundColor = "red"; button1.style.backgroundColor = button1Default; });。请尝试以下方法:

&#13;
&#13;
#button1,#button2 { padding: 15px 25px; font-size: 24px; text-align: center; cursor: pointer; outline: none; color: #fff; background-color: #4CAF50; border: none; border-radius: 15px; box-shadow: 0 9px #999; } 
#button1:hover {background-color: #3e8e41} 
#button1:active { box-shadow: 0 5px #666; transform: translateY(4px); }
&#13;
<div id='rightAlign'>
  <div id="but1">
    <button id="button1" onclick="">Click Me</button>
    <button id="button2">Click Me</button>
  </div>
</div>
&#13;
return balance;
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");    

button1.addEventListener("click", function(){
button1.style.backgroundColor = "red"
button2.style.backgroundColor = ''
})

button2.addEventListener("click", function(){
button2.style.backgroundColor = "red"
button1.style.backgroundColor = ''
})
<div id='rightAlign'>
  <div id="but1">
    <button id="button1">Click Me</button>
    <button id="button2">Click Me</button>
  </div>
</div>                                    

   

答案 2 :(得分:0)

这是你在找什么?

&#13;
&#13;
var button1 = document.getElementById("button1"); 
var button2 = document.getElementById("button2");

 button1.addEventListener("click", function(){
   button1.style.backgroundColor = "red";
   button2.style.backgroundColor = "";
 });

 button2.addEventListener("click", function(){
   button2.style.backgroundColor = "red";
   button1.style.backgroundColor = "";
 });
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
  <button id="button1">Click Me</button>
  <button id="button2">Click Me</button>
</body>
</html>
&#13;
&#13;
&#13;

寻找?