简体   繁体   中英

How to make score progress bar HTML/CSS/JS

I am trying to do a 5 segment progress bar for score keeping app. 2 Players, each will have their own progress bar (5 divs in grid next to each other). I have 2 buttons (P1 and P2) whenever one of those is pressed, point is added to appropriate player. I want to have a visual representation that will fill in one of 5 divs with a color upon adding a point. I do have a logic for changing score, and stopping game once one of the players hit 5 points. I don't want to use element, and I want for each progress bar to start filling segments from outer to inner (so player 2 will have reversed order) But I have no clue how to go about changing background color of a single segment for button presses. Should all scoreBox divs have unique IDs?

My score keeping mockup

HTML


    <div class="gameContainer">
        <div class="scoreContainer">
            <h1><span id="p1score">0</span> to <span id="p2score">0</span></h1>
        </div>
        <div class="scoreGfx">
            <div class="p1gfx">
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
            </div>
            <div class="p2gfx">
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
                <div class="scoreBox"></div>
            </div>
        </div>

I tried finding a way to select each box for button press, but wasn't successful.

To select a particular score box, you can use the :nth-child pseudo class.

For example, .p1gfx >:nth-child(1) gets the first score box of the first player, .p1gfx >:nth-child(2) gets the second score box of the first player, and so on.

I would recommend adding a CSS class for the background color. For example:

.point {
    background-color: green;
}

To add or remove color from a box, you can then just add or remove the CSS class to the element. For example, to change the background color of the first box of the first player to green, you can do this:

const box = document.querySelector('.p1gfx > :nth-child(1)');
box.classList.add('point');

Use unique id for each players: use unique id for player one segment and player two segment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM