在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来隐藏,但是其隐藏后仍然占据原来的空间。
test .titlediv{background-color: #505050;color:white;font-weight:bold;padding:10px;cursor:pointer } .contentdiv{border:3px solid #505050;height:100px;padding:10px; } click here(内容部分会隐藏,下面的内容会上来) this is some content to show and hide click here this is some content to show and hide click here(内容部分会隐藏,下面的内容不会上来) this is some content to show and hide click here this is some content to show and hide [Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
