简体   繁体   中英

Trying to rotate an image with JS when an element contains a certain class

Basically im trying to make it so that when i click on a question the arrow i have next to the question rotates 180 degrees. Right now my code doesnt rotate the arrows at all. Any help would be appreciated.

Heres my javascript code

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function () {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}

var img = document.getElementsByClassName("arrow");

if (button.classList.contains(active)) {
  img.style.transform = "rotate(180deg)";
}
    

Current result

One big reason this isn't working is that this line:

if (button.classList.contains(active)) { img.style.transform = "rotate(180deg)"; }

isn't inside of some function that triggers the arrow to rotate. It is evaluated when the page loads and then not used again. However, there are a few ways to improve your code.

Using classes to affect your style changes allows you better readability, flexibility and reusability. I also opted for querySelectorAll instead of getElementsByClassname and used a closest / querySelector combo to find adjacent elements rather than nextElementSibling

 document.querySelectorAll(".accordian").forEach(acc => { acc.addEventListener("click", e => { e.target.classList.toggle("active"); e.target.closest('.container').querySelector('.arrow').classList.toggle('active') e.target.closest('.container').querySelector('.content').classList.toggle('show') }); });
 .arrow { transition: all.5s; display: inline-block; }.arrow.active { transform: rotate(90deg); }.content { display: none; }.show { display: block; }
 <div class='container'> <a class='accordian' href='#'>click me</a> <span class='arrow'>></span> <div class='content'>Show//Hide content</div> </div> <div class='container'> <a class='accordian' href='#'>click me</a> <span class='arrow'>></span> <div class='content'>Show//Hide content</div> </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