简体   繁体   中英

Toggle style same as class in pure javascript

I've got some code where when a button is clicked it toggles an active class. At the same time I need to set a top-margin on the toggled element, which also needs to be removed once the button is clicked again and the toggled class is removed. I can't set the top-margin as part of the active class as I need to get the value of the margin dynamically by checking the height of another element.

This is the code I've got to toggle the class and add the margin

var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;

sizeBtn.addEventListener("click", function(e) {
    sizeItems.classList.toggle('size-toggle--active')
    sizeItems.style.marginTop = "-" + elementHeight + "px";
});

However, obviously this doesn't remove the style when the button is clicked again so basically I need to toggle the style just like the active class. Is there anyway to do this?

You need to check if className is there or not so the code could be:

var sizeBtn = document.querySelector(".size-toggle-btn");
var sizeItems = document.querySelector(".select-items");
var elementHeight = document.querySelector(".Detail-Container__inline").offsetHeight ;

sizeBtn.addEventListener("click", function(e) {
  if(sizeItems.classList.contains('size-toggle--active')) {
    sizeItems.classList.remove('size-toggle--active')
    sizeItems.style.marginTop = null;
  }
  else{
    sizeItems.classList.add('size-toggle--active')
    sizeItems.style.marginTop = "-" + elementHeight + "px";
  }
});

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