无法控制与 JavaScript 的另一个元素共享 css class 的 css 元素

Can't control a css element that shares a css class with another element with JavaScript

[仅供参考:进行 Udemy 教程挑战]

这里是html。它显示 2 个骰子。如你所见,它们共享 class 'dice.' 然后每个骰子也有自己的 class 用于控制单个项目,分别为 'dice1' 和 'dice2'。

<img src="dice-5.png" alt="Dice 1" class="dice dice1">
<img src="dice-5.png" alt="Dice 2" class="dice dice2">

这是所有这三个 classes、'dice'、'dice1'、'dice2.' 的 css 如您所见,'dice1' 和 'dice2' class 仅控制屏幕上的垂直位置。

.dice {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.dice1 {
    top: 260px;
}

.dice2 {
    top: 150px;
}

在这个骰子游戏开始时,两个骰子都不应该是可见的。为此,我使用 Javascript 通过以下代码控制显示。

document.querySelector('.dice').style.display = 'none';

出于某种原因,这只适用于 dice1。它不适用于 dice2。如果我添加一行额外的代码指定 class 'dice2',dice2 也会消失。但是,selecting class 'dice' 应该 select 他们两个。为什么这不起作用?

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

The Document method querySelector() returns the first Element within the document

使用querySelectorAll:

document.querySelectorAll('.dice').forEach( dice_Item=>dice_Item.style.display = 'none' );