如何用HTML/CSS/JS实现双向填充的5段分数进度条
解决方案
不需要给每个scoreBox设置唯一ID,利用父容器选择器结合元素索引就能精准控制分段颜色,下面是具体实现步骤:
1. 补充CSS样式
先定义进度条基础样式和填充状态的样式:
.scoreBox { width: 40px; height: 100px; border: 2px solid #333; display: inline-block; margin: 0 5px; background-color: #fff; } /* 填充状态的样式 */ .scoreBox.filled { background-color: #4CAF50; /* 可替换为你需要的颜色 */ } .p2gfx { /* 让P2进度条与P1对称显示,可选 */ display: flex; flex-direction: row-reverse; }
2. JS逻辑实现
结合你已有的计分逻辑,在加分后同步更新进度条:
// 获取页面元素 const p1ScoreEl = document.getElementById('p1score'); const p2ScoreEl = document.getElementById('p2score'); const p1Boxes = document.querySelectorAll('.p1gfx .scoreBox'); const p2Boxes = document.querySelectorAll('.p2gfx .scoreBox'); // 初始化分数 let p1Score = 0; let p2Score = 0; const maxScore = 5; // 加分核心函数 function addScore(player) { if (player === 'p1' && p1Score < maxScore) { p1Score++; p1ScoreEl.textContent = p1Score; updateProgressBar(p1Boxes, p1Score, false); // false表示正序填充 } else if (player === 'p2' && p2Score < maxScore) { p2Score++; p2ScoreEl.textContent = p2Score; updateProgressBar(p2Boxes, p2Score, true); // true表示倒序填充 } // 你的游戏结束逻辑 if (p1Score === maxScore || p2Score === maxScore) { document.getElementById('p1Btn').disabled = true; document.getElementById('p2Btn').disabled = true; alert(`${p1Score === maxScore ? '玩家1' : '玩家2'}获胜!`); } } // 更新进度条的工具函数 function updateProgressBar(boxes, score, isReverse) { // 先重置所有分段的填充状态 boxes.forEach(box => box.classList.remove('filled')); // 根据分数和填充顺序,为对应分段添加填充类 for (let i = 0; i < score; i++) { const index = isReverse ? boxes.length - 1 - i : i; boxes[index].classList.add('filled'); } } // 为按钮绑定点击事件(假设按钮ID为p1Btn、p2Btn) document.getElementById('p1Btn').addEventListener('click', () => addScore('p1')); document.getElementById('p2Btn').addEventListener('click', () => addScore('p2'));
3. 补充按钮HTML(若未添加)
在gameContainer内添加操作按钮:
<div class="btnContainer"> <button id="p1Btn">玩家1加分</button> <button id="p2Btn">玩家2加分</button> </div>
关键逻辑说明
- 用
querySelectorAll获取对应玩家的所有scoreBox,通过索引直接访问单个分段 - 填充顺序通过
isReverse参数控制:玩家1从左到右正序填充,玩家2从右到左倒序填充 - 每次加分后先重置所有分段状态,再根据当前分数重新填充,避免状态混乱
内容的提问来源于stack exchange,提问作者webPotato
相关产品推荐
相关产品推荐

