简体   繁体   中英

How do I make a paragraph or div disappear with javascript?

I am trying to use buttons to make paragraphs disappear with javascript, but when I make them "hidden", they still leave a big chunk of blank space. Is there a way I can remove that blank space?

The javascript:

function background(){
  document.getElementById("myBackground").style.visibility="visible";
   document.getElementById("favSubjects").style.visibility="hidden";
  document.getElementById("hobbies").style.visibility="hidden";
  document.getElementById("contactMe").style.visibility="hidden";
}

The html:

      <button onclick="background()" class="buttons b1" id="Background">
        My Background
      </button>
      <p id="myBackground">
        I am from ...
      </p>

You want something more like display:none which will actually hide the object (visibility:hidden and opacity:0 will make the object invisible, but still take up space).

Even still, you could make your life a little easier by using classes. Give all those elements the same class name and set a new class for hiding things. This example shows how you can access a group of elements that share a common class and toggle the hide/show.

 function background() { document.querySelectorAll('.hideable').forEach(el => el.classList.toggle('hidden')); }
 .hidden { display: none; }
 <div id='this' class='hideable'> Hide me </div> <span id='that' class='hideable'> Hide me </span> <ul> <li>Keep me</li> <li class='hideable'>Hide me</li> </ul> <button onclick='background()'>Toggle on/off elements</button>

尝试设置 display:none 隐藏并设置 display:block 显示。


You can use that simple way,

 function background() { var x = document.getElementById("myBackground"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
 <p id="myBackground"> I am from ... </p> <button onclick="background()" class="buttons b1" id="Background"> My Background </button>

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