JS中style.display与style.visibility的区别
本文通过实例说明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需再刷新一下页面才能执行]
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
