JS中style.display和style.visibility的區別
阿新 • • 發佈:2019-02-10
在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>