简体   繁体   中英

Css visibility hidden

I'm trying to create a toggle button through javascript without a button ID and the css element visibility hidden, I have been trying to google it but can't find any good answers, I can only found how you toggle by using style.display but that doesn't work when I use visibility hidden in css. The button name for the toggle button is button2 and the hidden button has Hbutton as the ID.

document.querySelector(button8).addEventListener(click, function () {
  document.querySelector("hiddenbutton").style.visibility = "visible";
});

Get the current style, and use a conditional.

document.querySelector(button8).addEventListener(click, function() {
  const button = document.querySelector("hiddenbutton");
  let current = getComputedStyle(button).getPropertyValue("visibility");

  button.style.visibility = current == "visible" ? "hidden" : "visible";
})

You can use the computed style to determine whether or not the element is visible.

 document.querySelector("button").addEventListener("click", function(){ let p = document.querySelector("p"); let visibility = getComputedStyle(p).visibility; if(visibility == "hidden") p.style.visibility = "visible"; else p.style.visibility = "hidden"; });
 p { visibility: hidden; }
 <p>I will disappear</p> <button>Toggle</button>

You can actually do this by toggling through classes which is more simple! Just create a class eg .hide and set the visibility to hidden. Whenever you click on the button, the selected button's class will be toggled through the given class( .hide ).

 document.querySelector('.toggle').addEventListener('click', () => { document.querySelector('.myBtn').classList.toggle('hide'); });
 .hide { visibility: hidden; }
 <button class="myBtn">You See Me!</button> <button class="toggle">toggle</button>

It is very simple:

document.querySelector(button8).addEventListener(click, function () {
  var element = document.querySelector("hiddenbutton")
  if (element.style.visibility == "visible") {
    element.style.visibility = "hidden"
  } else {
    element.style.visibility = "visible"
  }
});

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