css 当一个HTML元素被选中时,有没有办法从另一个HTML元素中删除一个类?

nzk0hqpo  于 2023-03-14  发布在  其他
关注(0)|答案(1)|浏览(123)

我正在尝试做一个简单的石头剪刀布游戏,电脑生成的选项会用一个彩色边框突出显示,当另一个选项被选中时,边框会恢复正常。目前我正在使用.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;
}
axr492tv

axr492tv1#

/*Can try this*/

function getComputerChoice() {
  const choices = {
    Rock: "#computerRock",
    Paper: "#computerPaper",
    Scissors: "#computerScissors",
  };
  
  const classToAdd = "computerActive";
  const selection = Object.keys(choices)[Math.floor(Math.random() * 3)];
  
  Object.values(choices).forEach(selector => {
    const element = document.querySelector(selector);
    element.classList.remove(classToAdd);
    if (selector === choices[selection]) {
      element.classList.add(classToAdd);
    }
  });
  
  return selection;
}

相关问题