日期:2014-05-16  浏览次数:20341 次

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

在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>