JS中style.display与style.visibility的区别

作者:小括号

时间:2026-10-27

浏览:344

本文通过实例说明JavaScript中style.display与style.visibility在隐藏元素时的区别。style.display设为none时元素脱离文档流,后续元素填补空间;而style.visibility设为hidden时元素仍占据原有位置。

文章目录

style.display与style.visibility的区别

在JavaScript中,可以通过设置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: #505050;color:white;font-weight:bold;padding:10px;cursor:pointer } .contentdiv{border:3px solid #505050;height:100px;padding:10px; } </style>  </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> 

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章