我正在尝试做一个简单的石头剪刀布游戏,电脑生成的选项会用一个彩色边框突出显示,当另一个选项被选中时,边框会恢复正常。目前我正在使用.classList.add()和.classList.remove()来实现这一点。有没有办法清理这个代码,因为现在感觉非常手动。
<script>
function getComputerChoice() {
// Generating Rock, Paper or Scissors
let choices = ["Scissors", "Paper", "Rock"]
let selection = choices[Math.floor(Math.random() * choices.length)]
rock = document.querySelector("#computerRock")
paper = document.querySelector("#computerPaper")
scissors = document.querySelector("#computerScissors")
if (selection === "Rock") {
rock.classList.add("computerActive")
paper.classList.remove("computerActive")
scissors.classList.remove("computerActive")
}
else if (selection === "Paper") {
paper.classList.add("computerActive")
rock.classList.remove("computerActive")
scissors.classList.remove("computerActive")
}
else if (selection === "Scissors") {
scissors.classList.add("computerActive")
rock.classList.remove("computerActive")
paper.classList.remove("computerActive")
}
return selection
}
</script>
// CSS code for reference
.computerActive {
transform: scale(1.1);
border: 5px solid red;
box-shadow: 0 0 5px black;
}
1条答案
按热度按时间axr492tv1#