使用 DOM 操作 css 可见性

发布于 2025-01-09 03:30:26 字数 6485 浏览 0 评论 0原文

伙计们。我对 JS 还很陌生,而且我已经被一个问题困扰了一段时间了。我的代码是一个简单的骰子游戏。当您按下按钮时,您会调用一个 JS 函数,该函数会随机化 12 个骰子图像,并根据骰子值显示某些图像和获胜者的标题。

问题是我使用 DOM 在 HTML 元素中添加和删除类,以通过 CSS 控制元素的可见性。有两个循环可以“清理”之前运行中的元素。第一个似乎有效(arrayImagesClasses),第二个我在控制台上收到错误(arrayTitleClasses)。

我的疑问是:

  • 为什么我的第二个循环不起作用?
  • 这是进行这种操纵的正确方法吗? (我的解决方案看起来“愚蠢”)

提前致谢。

'''

function getRandomDiceNumber(){
  return Math.ceil(Math.random() * 6)
}

function pickWinner() {
  // Remove visibility class from all dice images in previous runs
  var arrayImagesClasses = document.querySelectorAll("[class*='-img']");
  for ( i = 0; i <= 11; i++ ) {
    arrayImagesClasses[i].classList.remove("dice-img-visibility");
  }

  //Remove visibility class from titles
  var arrayTitleClasses = document.querySelectorAll("[class*='-title']");
  for ( j = 0; j <= 11; j++ ) {
    arrayTitleClasses[j].classList.remove("pick-winner");
  }

  // get random dice (1 - 6) number
  var randomNumberPlayerOne = getRandomDiceNumber();
  var randomNumberPlayerTwo = getRandomDiceNumber();

  // use same dice function to access index of dice imgages array
  var diceImgPlayerOne = document.querySelector(".p1-dice"+ randomNumberPlayerOne + "-img");
  var diceImgPlayerTwo = document.querySelector(".p2-dice"+ randomNumberPlayerTwo + "-img");

  if (randomNumberPlayerOne > randomNumberPlayerTwo) {
    document.querySelector(".p1-win-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");

  } else if (randomNumberPlayerOne < randomNumberPlayerTwo) {
    document.querySelector(".p2-win-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");

  } else {
    document.querySelector(".tie-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");
  }
}
body {
  text-align: center;
  font-family: 'Montserrat', sans-serif;
  background-color: #495371;
  color: #EEEEEE;
}

img {
  width: 290px;
  height: auto;
  visibility: visible;
  /* position: absolute; */
  margin: auto;
}

h1 {
  font-size: 5rem;
}

/* Titles */
.p1-win-title {
  display: none;
}
.p2-win-title {
  display: none;
}
.tie-title {
  display: none;
}

.pick-winner {
  /* display: visible; */
  display: block;
}

/* Players Dice */
.player1-div {
  display: inline-block;
  width: 400px;
  height: 400px;
}

.player2-div {
  display: inline-block;
  width: 400px;
  height: 400px;
}

.header-p1, .header-p2 {
  font-size: 2rem;
  font-weight: 400;
}

.dice-p1-div {
  position: relative;
}

.dice-p2-div {
  position: relative;
}
.p1-dice1-img, .p1-dice2-img,
.p1-dice3-img, .p1-dice4-img,
.p1-dice5-img, .p1-dice6-img {
  position: absolute;
  left: 60px;
  display: none;
}

.p2-dice1-img, .p2-dice2-img,
.p2-dice3-img, .p2-dice4-img,
.p2-dice5-img, .p2-dice6-img {
  position: absolute;
  left: 60px;
  display: none;
}

.dice-img-visibility {
  display: inline;
}

.button-div{
  margin: 3% auto;
}

.button-roll {
  height: 70px;
  width: 200px;
  border-radius: 10px;
  border: 0;
  font-size: 1.8Rem;
  font-family: 'Montserrat', sans-serif;
  font-weight: bold;
}

.footer {
  bottom: 0;
  position: static;
  width: 100%;
  /* margin: 2% auto; */
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <!-- css -->
    <link rel="stylesheet" href="css/styles.css">

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Roboto&display=swap" rel="stylesheet">

    <title></title>
  </head>
  <body>
    <!-- Title and winner -->
    <div class="">
      <h1 class="main-title">Dice Game</h1>
      <h1 class="p1-win-title">Player 1 Wins!</h1>
      <h1 class="p2-win-title">Player 2 Wins!</h1>
      <h1 class="tie-title">It's a tie!</h1>
    </div>

    <!-- Dice header -->
    <div class="game-area">
      <div class="player1-div">
        <div class="player1-div-header">
          <h3 class="header-p1">Player 1</h3>
        </div>
        <div class="dice-p1-div">
          <img class="p1-dice1-img" src="images/dice1.png" alt="">
          <img class="p1-dice2-img" src="images/dice2.png" alt="">
          <img class="p1-dice3-img" src="images/dice3.png" alt="">
          <img class="p1-dice4-img" src="images/dice4.png" alt="">
          <img class="p1-dice5-img" src="images/dice5.png" alt="">
          <img class="p1-dice6-img" src="images/dice6.png" alt="">
        </div>
      </div>

      <div class="player2-div">
        <div class="player2-div-header">
          <h3 class="header-p2">Player 2</h3>
        </div>
        <div class="dice-p2-div">
          <img class="p2-dice1-img" src="images/dice1.png" alt="">
          <img class="p2-dice2-img" src="images/dice2.png" alt="">
          <img class="p2-dice3-img" src="images/dice3.png" alt="">
          <img class="p2-dice4-img" src="images/dice4.png" alt="">
          <img class="p2-dice5-img" src="images/dice5.png" alt="">
          <img class="p2-dice6-img" src="images/dice6.png" alt="">
        </div>
      </div>
    </div>

    <!-- Buttton -->
    <div class="button-div">
      <button class="button-roll" onclick="pickWinner();" type="button" name="button">Roll</button>
    </div>

    <!-- Footer -->
    <div class="footer">
      <p>Dice Game</p>
      <p>Alexandre Luiz Elias</p>
    </div>
  <script src="js/index.js" charset="utf-8"></script>
  </body>
</html>

'''

guys. I'm pretty new to JS and i'm stuck with a problem for quite sometime now. My code is a simple dice game. When you press a button, you call a JS function that randomize 12 dice images and display certain images and a title with the winner depending on the dice value.

The problem is that i'm using DOM to add and remove a class from my HTML elements to control the visibility of the element throug CSS. There's two loops to "clean" my elements from previous runs. The first one seems to work (arrayImagesClasses) and the second i get an error on console (arrayTitleClasses).

My doubts are:

  • Why does my second loop does not work?
  • Is that a proper way to do that manipulation? (my solution looks "dumb")

Thanks in advance.

'''

function getRandomDiceNumber(){
  return Math.ceil(Math.random() * 6)
}

function pickWinner() {
  // Remove visibility class from all dice images in previous runs
  var arrayImagesClasses = document.querySelectorAll("[class*='-img']");
  for ( i = 0; i <= 11; i++ ) {
    arrayImagesClasses[i].classList.remove("dice-img-visibility");
  }

  //Remove visibility class from titles
  var arrayTitleClasses = document.querySelectorAll("[class*='-title']");
  for ( j = 0; j <= 11; j++ ) {
    arrayTitleClasses[j].classList.remove("pick-winner");
  }

  // get random dice (1 - 6) number
  var randomNumberPlayerOne = getRandomDiceNumber();
  var randomNumberPlayerTwo = getRandomDiceNumber();

  // use same dice function to access index of dice imgages array
  var diceImgPlayerOne = document.querySelector(".p1-dice"+ randomNumberPlayerOne + "-img");
  var diceImgPlayerTwo = document.querySelector(".p2-dice"+ randomNumberPlayerTwo + "-img");

  if (randomNumberPlayerOne > randomNumberPlayerTwo) {
    document.querySelector(".p1-win-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");

  } else if (randomNumberPlayerOne < randomNumberPlayerTwo) {
    document.querySelector(".p2-win-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");

  } else {
    document.querySelector(".tie-title").classList.toggle("pick-winner");
    diceImgPlayerOne.classList.toggle("dice-img-visibility");
    diceImgPlayerTwo.classList.toggle("dice-img-visibility");
  }
}
body {
  text-align: center;
  font-family: 'Montserrat', sans-serif;
  background-color: #495371;
  color: #EEEEEE;
}

img {
  width: 290px;
  height: auto;
  visibility: visible;
  /* position: absolute; */
  margin: auto;
}

h1 {
  font-size: 5rem;
}

/* Titles */
.p1-win-title {
  display: none;
}
.p2-win-title {
  display: none;
}
.tie-title {
  display: none;
}

.pick-winner {
  /* display: visible; */
  display: block;
}

/* Players Dice */
.player1-div {
  display: inline-block;
  width: 400px;
  height: 400px;
}

.player2-div {
  display: inline-block;
  width: 400px;
  height: 400px;
}

.header-p1, .header-p2 {
  font-size: 2rem;
  font-weight: 400;
}

.dice-p1-div {
  position: relative;
}

.dice-p2-div {
  position: relative;
}
.p1-dice1-img, .p1-dice2-img,
.p1-dice3-img, .p1-dice4-img,
.p1-dice5-img, .p1-dice6-img {
  position: absolute;
  left: 60px;
  display: none;
}

.p2-dice1-img, .p2-dice2-img,
.p2-dice3-img, .p2-dice4-img,
.p2-dice5-img, .p2-dice6-img {
  position: absolute;
  left: 60px;
  display: none;
}

.dice-img-visibility {
  display: inline;
}

.button-div{
  margin: 3% auto;
}

.button-roll {
  height: 70px;
  width: 200px;
  border-radius: 10px;
  border: 0;
  font-size: 1.8Rem;
  font-family: 'Montserrat', sans-serif;
  font-weight: bold;
}

.footer {
  bottom: 0;
  position: static;
  width: 100%;
  /* margin: 2% auto; */
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <!-- css -->
    <link rel="stylesheet" href="css/styles.css">

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Roboto&display=swap" rel="stylesheet">

    <title></title>
  </head>
  <body>
    <!-- Title and winner -->
    <div class="">
      <h1 class="main-title">Dice Game</h1>
      <h1 class="p1-win-title">Player 1 Wins!</h1>
      <h1 class="p2-win-title">Player 2 Wins!</h1>
      <h1 class="tie-title">It's a tie!</h1>
    </div>

    <!-- Dice header -->
    <div class="game-area">
      <div class="player1-div">
        <div class="player1-div-header">
          <h3 class="header-p1">Player 1</h3>
        </div>
        <div class="dice-p1-div">
          <img class="p1-dice1-img" src="images/dice1.png" alt="">
          <img class="p1-dice2-img" src="images/dice2.png" alt="">
          <img class="p1-dice3-img" src="images/dice3.png" alt="">
          <img class="p1-dice4-img" src="images/dice4.png" alt="">
          <img class="p1-dice5-img" src="images/dice5.png" alt="">
          <img class="p1-dice6-img" src="images/dice6.png" alt="">
        </div>
      </div>

      <div class="player2-div">
        <div class="player2-div-header">
          <h3 class="header-p2">Player 2</h3>
        </div>
        <div class="dice-p2-div">
          <img class="p2-dice1-img" src="images/dice1.png" alt="">
          <img class="p2-dice2-img" src="images/dice2.png" alt="">
          <img class="p2-dice3-img" src="images/dice3.png" alt="">
          <img class="p2-dice4-img" src="images/dice4.png" alt="">
          <img class="p2-dice5-img" src="images/dice5.png" alt="">
          <img class="p2-dice6-img" src="images/dice6.png" alt="">
        </div>
      </div>
    </div>

    <!-- Buttton -->
    <div class="button-div">
      <button class="button-roll" onclick="pickWinner();" type="button" name="button">Roll</button>
    </div>

    <!-- Footer -->
    <div class="footer">
      <p>Dice Game</p>
      <p>Alexandre Luiz Elias</p>
    </div>
  <script src="js/index.js" charset="utf-8"></script>
  </body>
</html>

'''

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清眉祭 2025-01-16 03:30:26

您无法确定数组的长度始终为 11。请尝试以下代码;

//Remove visibility class from titles
  var arrayTitleClasses = Array.from(document.querySelectorAll("[class*='-title']"));
  for ( j = 0; j <= arrayTitleClasses.length; j++ ) {
    arrayTitleClasses[j].classList.remove("pick-winner");
  }

You cant be sure the lengths of your arrays will always be 11. Try the following code below;

//Remove visibility class from titles
  var arrayTitleClasses = Array.from(document.querySelectorAll("[class*='-title']"));
  for ( j = 0; j <= arrayTitleClasses.length; j++ ) {
    arrayTitleClasses[j].classList.remove("pick-winner");
  }
野心澎湃 2025-01-16 03:30:26

发生这种情况是因为当您使用 var arrayTitleClasses = document.querySelectorAll("[class*='-title']"); 获取 arrayTitleClasses 并循环遍历它时。该数组只有 4 个元素长,您将循环它 11 次。

It happens because when you grab the arrayTitleClasses with var arrayTitleClasses = document.querySelectorAll("[class*='-title']"); and loop over it. This array is only 4 elements long and you are looping trough it 11 times.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文