最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make buttons change colors when clicked? - Stack Overflow

programmeradmin0浏览0评论

I set up 3 buttons and am wondering how to make them change colors when clicked on. 'Yes' should be green 'No' should be red 'Maybe' should be red also.

<!DOCTYPE html>

<html lang="en">
<head>
  <link
    href=":wght@500&display=swap"
    rel="stylesheet">
  <link href="styles.css" rel="stylesheet">
  <title>Trivia!</title>

  <script></script>

</head>
<body>

<div class="jumbotron">
  <h1>Trivia!</h1>
</div>

<div class="container">

  <div class="section">
    <h2>Part 1: Multiple Choice</h2>
    <hr>

    <h3>Do you love me?
      <h3>

        <button id="q1button">Yes</button>
        <button id="q2button">No</button>
        <button id="q3button">Maybe</button>

  </div>

</div>
</body>
</html>

I set up 3 buttons and am wondering how to make them change colors when clicked on. 'Yes' should be green 'No' should be red 'Maybe' should be red also.

<!DOCTYPE html>

<html lang="en">
<head>
  <link
    href="https://fonts.googleapis./css2?family=Montserrat:wght@500&display=swap"
    rel="stylesheet">
  <link href="styles.css" rel="stylesheet">
  <title>Trivia!</title>

  <script></script>

</head>
<body>

<div class="jumbotron">
  <h1>Trivia!</h1>
</div>

<div class="container">

  <div class="section">
    <h2>Part 1: Multiple Choice</h2>
    <hr>

    <h3>Do you love me?
      <h3>

        <button id="q1button">Yes</button>
        <button id="q2button">No</button>
        <button id="q3button">Maybe</button>

  </div>

</div>
</body>
</html>
Share Improve this question edited Jan 15, 2024 at 15:56 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Jan 19, 2021 at 15:52 joeduniajoedunia 311 silver badge3 bronze badges 3
  • Is this Java or Javascript? They are two pletely different languages. – Rojo Commented Jan 19, 2021 at 15:56
  • I meant Javascript – joedunia Commented Jan 19, 2021 at 16:02
  • 3 FYI, your <h3> tag is not closed. – terrymorse Commented Jan 19, 2021 at 16:39
Add a ment  | 

7 Answers 7

Reset to default 3

Do you mean this?

button:focus {
    outline: none;
    border: 1px solid black;
}
#q1button:focus {
    background-color: green;
    color: pink;
}
#q2button:focus {
    background-color: red;
    color: white;
}
#q3button:focus {
    background-color: yellow;
    color: black;
}
    <body>

        <div class="jumbotron">
            <h1>Trivia!</h1>
        </div>

        <div class="container">

            <div class="section">
                <h2>Part 1: Multiple Choice</h2>
                <hr>

                <h3>Do you love me?<h3>
                    
                <button id="q1button">Yes</button>
                <button id="q2button">No</button>
                <button id="q3button">Maybe</button>

            </div>

        </div>
    </body>

You can do it using javascript. I think something like this works for you.

<!DOCTYPE html>
<html>

<body>

    <div class="jumbotron">
        <h1>Trivia!</h1>
    </div>

    <div class="container">

        <div class="section">
            <h2>Part 1: Multiple Choice</h2>
            <hr>

            <h3>Do you love me?<h3>
                
            <button id="q1button" onclick="this.style.background = 'green'">Yes</button>
            <button id="q2button" onclick="this.style.background = 'red'">No</button>
            <button id="q3button" onclick="this.style.background = 'red'">Maybe</button>

        </div>

    </div>
</body>
</html>

Edit:

Work around for all of them getting highlighted.

<!DOCTYPE html>
<html>

<body>
    <div class="jumbotron">
        <h1>Trivia!</h1>
    </div>
    <div class="container">
        <div class="section">
            <h2>Part 1: Multiple Choice</h2>
            <hr>
            <h3>Do you love me?<h3>
            <button id="q1button" onclick="changeBg(this);">Yes</button>
            <button id="q2button" onclick="changeBg(this);">No</button>
            <button id="q3button" onclick="changeBg(this);">Maybe</button>
        </div>
    </div>
    <script>
        function changeBg(button){
            if(button.id == "q1button"){
                button.style.background = "green";
                document.getElementById("q2button").style.background = "transparent";
                document.getElementById("q3button").style.background = "transparent";
            }
            else if(button.id == "q2button"){
                button.style.background = "red";
                document.getElementById("q1button").style.background = "transparent";
                document.getElementById("q3button").style.background = "transparent";
            }
            if(button.id == "q3button"){
                button.style.background = "red";
                document.getElementById("q1button").style.background = "transparent";
                document.getElementById("q2button").style.background = "transparent";
            }
        }
    </script>
</body>
</html>

Try this :

<style>
 .yes:focus {
  background-color: green;
 }
.no:focus {
 background-color: red;
}
.maybe:focus {
 background-color: yellow;
}
</style>
<button class="yes">Yes</button>
<button class="no">No</button>
<button class="maybe">Maybe</button>
Let me know if it works.

You can achieve this with just CSS and some changes to the HTML.

In the example I use labels shaped like buttons to trigger inputs which will control the visual aesthetic of the buttons. This is handled in the CSS with the :checked and adjacent + selectors to modify the colors of the label .button.

.inputController {
  display: none;
}
.inputController:checked + .button-greenCK {
  background-color: green;
}
.inputController:checked + .button-redCK {
  background-color: red;
} 

.button {
  font-size: 0.65em;
  background-color: white;
  border-radius: 5px;
  padding: 5px 10px;
  border: 1px solid lightgrey;
  box-shadow: 3px 3px 3px rgba(0,0,0,0.25);
  cursor: pointer;
  margin-right: 5px;
}
.button_label {}
<html lang="en">
    <head>
        <link href="https://fonts.googleapis./css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="styles.css" rel="stylesheet">
        <title>Trivia!</title>

        <script>

        </script>

    </head>
    <body>

        <div class="jumbotron">
            <h1>Trivia!</h1>
        </div>

        <div class="container">

            <div class="section">
                <h2>Part 1: Single Choice</h2>
                <hr>

                <h3>Do you love me?<h3>
                
                <input id="q1button" name="trivia1" class="inputController" type="radio"/>
                <label class="button button-greenCK" for="q1button">
                  <span class="button_value">Yes</span>
                </label>
                
                <input id="q2button" name="trivia1" class="inputController" type="radio"/>
                <label class="button button-redCK" for="q2button">
                  <span class="button_value">No</span>
                </label>
                
                <input id="q3button" name="trivia1" class="inputController" type="radio"/>
                <label class="button button-redCK" for="q3button">
                  <span class="button_label">Maybe</span>
                </label>

            </div>

        </div>
        
        <div class="container">

            <div class="section">
                <h2>Part 2: Multiple Choice</h2>
                <hr>

                <h3>Do you love me?<h3>
                
                <input id="q4button" name="trivia2" class="inputController" type="checkbox"/>
                <label class="button button-greenCK" for="q4button">
                  <span class="button_value">Yes</span>
                </label>
                
                <input id="q5button" name="trivia2" class="inputController" type="checkbox"/>
                <label class="button button-redCK" for="q5button">
                  <span class="button_value">No</span>
                </label>
                
                <input id="q6button" name="trivia2" class="inputController" type="checkbox"/>
                <label class="button button-redCK" for="q6button">
                  <span class="button_label">Maybe</span>
                </label>

            </div>

        </div>
    </body>
</html>

You could use jQuery to add a class name stored in a data attribute. That makes it easy for you to decide the color's button directly in the HTML markup.

Notice that removing the color class restores the button exactly as it was before.

$(".answer").on("click", function(){
  
  // Reset other answers.
  $(".answer").removeClass("red green")

  // Use the classname stored in the button's data attribute
  $(this).addClass($(this).data("color"))
})
.green{
  background: green;
}
.red{
  background: red;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis./css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">


<div class="jumbotron">
  <h1>Trivia!</h1>
</div>

<div class="container">

  <div class="section">
    <h2>Part 1: Multiple Choice</h2>
    <hr>

    <h3>Do you love me?</h3>

        <button class="answer" id="q1button" data-color="green">Yes</button>
        <button class="answer" id="q2button" data-color="red">No</button>
        <button class="answer" id="q3button" data-color="red">Maybe</button>

  </div>

</div>

The same in plain JS is:

let btns = document.querySelectorAll(".answer")

btns.forEach(function(btn){

  btn.addEventListener("click", function(){
  
    // Reset other answers.
    btns.forEach(function(btn){
      btn.classList.remove("red")
      btn.classList.remove("green")
    })
    
    // Use the classname stored in the button's data attribute
    this.classList.add(this.getAttribute("data-color"))
  })
})
.green{
  background: green;
}
.red{
  background: red;
}
<link href="https://fonts.googleapis./css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">


<div class="jumbotron">
  <h1>Trivia!</h1>
</div>

<div class="container">

  <div class="section">
    <h2>Part 1: Multiple Choice</h2>
    <hr>

    <h3>Do you love me?</h3>

        <button class="answer" id="q1button" data-color="green">Yes</button>
        <button class="answer" id="q2button" data-color="red">No</button>
        <button class="answer" id="q3button" data-color="red">Maybe</button>

  </div>

</div>

If you need to keep the color even if the button is not focused you need to use JS to maintain the button state. You may add a click event listener on a mon parent and if the target of that event is a button just toggle an active class on it.

When a button is clicked it could be reasonable to unselect the previous choice (if any) in the same section, but in case concurrent selections are allowed then remove the inner if block.

document.body.addEventListener('click', (ev) => {

  let currentTgt       = ev.target;
  let previousSelected, 
      section;
  
  /* a button is clicked? */
  if (currentTgt.matches('button')) {

    /* ment the next 'if' block if multiple buttons 
     * selection is allowed at the same time. 
     *
     * Is a button already active and that button is not
     * the same button I've just clicked? Then remove the
     * active class from that button
     */
    section = currentTgt.closest('.section');
    previousSelected = section.querySelector('.active');
    if (previousSelected && currentTgt !== previousSelected) {
       previousSelected.classList.remove('active');
    }

    currentTgt.classList.toggle('active');
  }
})
.active {
    color: red;
    
    &:where(.q1button) { 
        color: green 
    }
}
<div class="section">
  <h2>Question #1</h2>
  <button class="q1button">Yes</button>
  <button class="q2button">No</button>
  <button class="q3button">Maybe</button>
</div>

<div class="section">
  <h2>Question #2</h2>
  <button class="q1button">Yes</button>
  <button class="q2button">No</button>
  <button class="q3button">Maybe</button>
</div>

As a side note I suggest to use classes instead of id for the buttons if you plan to have more than one section with multiple questions (and buttons)

You can use a javascript event listener, and change the color like that when it is clicked on.

You also have to unset the other buttons when a different one is pushed.

const btn1= $('#q1button');
const btn2= $('#q2button');
const btn3= $('#q3button');

btn1.click( function() {
    btn1.css('background', 'green');
    btn2.css('background', 'initial');
    btn3.css('background', 'initial');
});

btn2.click( function() {
    btn1.css('background', 'initial');
    btn2.css('background', 'red');
    btn3.css('background', 'initial');
});

btn3.click( function() {
    btn1.css('background', 'initial');
    btn2.css('background', 'initial');
    btn3.css('background', 'red');
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

    <div class="jumbotron">
        <h1>Trivia!</h1>
    </div>

    <div class="container">

        <div class="section">
            <h2>Part 1: Multiple Choice</h2>
            <hr>

            <h3>Do you love me?<h3>
                
            <button id="q1button">Yes</button>
            <button id="q2button">No</button>
            <button id="q3button">Maybe</button>

        </div>

    </div>
</body>

发布评论

评论列表(0)

  1. 暂无评论