JS中style.display和style.visibility的區別

來源:互聯網
上載者:User

標籤:blog   his   之間   hidden   text   style   控制   文檔   ble   

在JS中可以通過設定style.display或者style.visibility屬性來控制元素是否顯示,在style.display=block和style.visibility=visible的時候,元素被顯示,在style.display=none和style.visibility=hidden的時候,元素被隱藏。它們之間最大的區別是通過style.display=none隱藏的時候,元素不佔據原來的位置,從文檔流中脫離,後續的元素填補其位置。通過style.visibility=hidden隱藏的時候,元素仍然佔據原來的位置,只是被隱藏。

下面的例子說明了這種區別:在這個例子中,divContent1和divContent2隱藏的時候用的是style.display=none,這時候,後面的div會向上移動,佔據已經隱藏的div的空間。divContent3和divContent4用的是style.visibility=hidden來隱藏,但是其隱藏後仍然佔據原來的空間。

<html>  <head>  <title>test</title>  <meta http-equiv=content-type content="text/html; charset=gb2312">  <style>  .titlediv{background-color:#eee;color:white;font-weight:bold;padding:10px;cursor:pointer }  .contentdiv{border:3px solid blue;height:100px;padding:10px; }  </style>  <script type="text/javascript">    function toggle(divid){      var odiv = document.getElementById(divid);      odiv.style.display=(odiv.style.display=="none")?"block":"none";  }    function showhide(divid){      var odiv = document.getElementById(divid);      odiv.style.visibility=(odiv.style.visibility=="visible")?"hidden":"visible";  }  </script>      </head>    <body >        <div class="titlediv" onclick="toggle(‘divContetn1‘)">click here</div>       <div class="contentdiv" id="divContetn1">this is some content to show and hide      </div>      <p> </p>      <div class="titlediv" onclick="toggle(‘divContetn2‘)">click here</div>       <div class="contentdiv" id="divContetn2">this is some content to show and hide      </div>       <p> </p>      <div class="titlediv" onclick="showhide(‘divContetn3‘)">click here</div>       <div class="contentdiv" id="divContetn3">this is some content to show and hide      </div>      <p> </p>      <div class="titlediv" onclick="showhide(‘divContetn4‘)">click here</div>       <div class="contentdiv" id="divContetn4">this is some content to show and hide      </div>          </body>    </html>  

 

JS中style.display和style.visibility的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.