CSS中的display:none和visibility:hidden的区别

二者都是隐藏HTML元素,在视觉效果上没有区别,但在一些DOM操作中二者还是有所不同的。
display:none;
使用该属性后,HTML元素(对象)的宽度、高度等各种属性值都将“丢失”;
visibility:hidden;
使用该属性后,HTML元素(对象)仅仅是在视觉上看不见(完全透明),而它所占据的空间位置仍然存在,也即是说它仍具有高度、宽度等属性值。

具体区别请看演示代码吧:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" lang="gb2312">
 3 <head>
 4 <head>
 5 <title> 实例演示:CSS中的display:none和visible:hidden的区别 </title>
 6 <meta http-equiv="content-type" content="text/html; charset=gb2312" />
 7 <meta http-equiv="content-type" content="text/html; charset=gb2312" />
 8 <meta name="author" content="枫岩,CnLei.y.l@gmail.com">
 9 <meta name="copyright" content="http://www.cnlei.com" />
10 </head>
11 <body>
12 <p><a href="javascript:alert($('CnLei_1').innerHTML+'的宽度:\n'+GetXYWH($('CnLei_1')).W);">点击这里 display:none;</a></p>
13 <p><a href="javascript:alert($('CnLei_2').innerHTML+'的宽度:\n'+GetXYWH($('CnLei_2')).W);">点击这里 visibility:hidden;</a></p>
14 <div id="CnLei_1" style="display:none;">CnLei_1</div>
15 <div id="CnLei_2" style="visibility:hidden;">CnLei_2</div>
16 
17 <script type="text/javascript">
18 var w3c=(document.getElementById)? true: false;
19 var agt=navigator.userAgent.toLowerCase();
20 var ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (agt.indexOf("omniweb") == -1));
21 var ie5=(w3c && ie)? true : false;
22 var ns6=(w3c && (navigator.appName=="Netscape"))? true: false;
23 
24 function $(o){
25 return document.getElementById(o)?document.getElementById(o):o;
26 }
27 
28 function GetXYWH(o){
29  var o=$(o);
30  var nLt=0;
31  var nTop=0;
32  var offsetParent = o;
33  while (offsetParent!=null && offsetParent!=document.body) {
34  nLt+=offsetParent.offsetLeft;
35  nTop+=offsetParent.offsetTop;
36  if(!ns6){
37  parseInt(offsetParent.currentStyle.borderLeftWidth)>0?nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
38  parseInt(offsetParent.currentStyle.borderTopWidth)>0?nTop+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
39  }
40  offsetParent=offsetParent.offsetParent;
41  }
42  return {X:nLt,Y:nTop,W:o.offsetWidth,H:o.offsetHeight};
43 }
44 </script>
45 </body>
46 </html>

 

posted @ 2013-12-26 14:13  朋友博客集  阅读(207)  评论(0编辑  收藏  举报