简体   繁体   中英

Can't seem to apply classList.toggle in a loop

I'm currently trying to switch between images. I have a couple of images stacked on top of each other and initially all of them have a display:none; . I want when I click a button a random image to appear on the screen. Selected every picture with querySelectorAll , made a random number generator and my goal was to iterate through them, and the number which is picked at the moment would signify which picture I was going to make visible. The problem is that in the console I can see that it's trying to toggle the class but nothing happens

Code for reference:

var button = document.querySelector(".btn-roll");

button.addEventListener("click", function() {
  var images = document.querySelectorAll(".dice");
  for (var i = 0; i < 6; i++) {
  var number =  Math.floor((Math.random() * 6) + 0);
  }

  for(var i = 0; i < images.length; i++) {
    images[number].classList.toggle("Appear");
  }
})

CSS for reference:

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

.Appear {
  display:block;
}

Additionally if there's something wrong with my for loop I tried adding all the images in an array and iterating through it as well, with no success as well.

A few things to fix:

  • number is not defined before it is used
  • You are calculating number 6 times, only needs to happen once.
  • You are calling toggle but not telling it if it should toggle off or on (Does not work in IE11)
  • You are always just toggeling number and not the entire list.

 var button = document.querySelector(".btn-roll"); button.addEventListener("click", function() { var images = document.querySelectorAll(".dice"); var number = Math.floor((Math.random() * 6) + 0); for(var i = 0; i < images.length; i++) { images[i].classList.toggle("Appear", i === number); } }) 
 .dice { position: absolute; left: 50%; top: 178px; transform: translateX(-50%); height: 100px; box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10); display: none; } .Appear { display:block; } 
 <button class="btn-roll">Roll</button> <div class="dice">1</div> <div class="dice">2</div> <div class="dice">3</div> <div class="dice">4</div> <div class="dice">5</div> <div class="dice">6</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM