CSS display:none和visibility:hidden的区别

一句话概括:使用CSS display:none属性后,HTML元素(对象)的宽度、高度等各种属性值都将“丢失”;而使用visibility:hidden属性后,HTML元素(对象)仅仅是在视觉上看不见(完全透明),而它所占据的空间位置仍然存在。

详情如下:

CSS display:none和visibility:hidden的区别

visibility:hidden隐藏,但在浏览时保留位置;CSS display:none视为不存在,且不加载!

Overflow属性值{visible|hidden|scroll|auto}前提是先要限制DIV的宽度(width)和高度(height)。二者都是隐藏HTML元素,在视觉效果上没有区别,但在一些DOM操作中二者还是有所不同的。

CSS display:none;

使用该属性后,HTML元素(对象)的宽度、高度等各种属性值都将“丢失”;

visibility:hidden;

使用该属性后,HTML元素(对象)仅仅是在视觉上看不见(完全透明),而它所占据的空间位置仍然存在,也即是说它仍具有高度、宽度等属性值。

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

  1. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml"lang="gb2312">
  4. <head>
  5. <head>
  6. <title>实例演示:CSS display:none和visible:hidden的区别</title>
  7. <metahttp-equivmetahttp-equiv="content-type"content="text/html;charset=gb2312"/>
  8. <metahttp-equivmetahttp-equiv="content-type"content="text/html;charset=gb2312"/>
  9. <metanamemetaname="author"content="枫岩,CnLei.y.l@gmail.com">
  10. <metanamemetaname="copyright"content="http://www.cnlei.com"/>
  11. </head>
  12. <body>
  13. <p><ahrefahref="javascript:alert($('CnLei_1').innerHTML+'的宽度:\n'
  14. +GetXYWH($('CnLei_1')).W);">点击这里CSS display:none;</a></p>
  15. <p><ahrefahref="javascript:alert($('CnLei_2').innerHTML+'的宽度:\n'
  16. +GetXYWH($('CnLei_2')).W);">点击这里visibility:hidden;</a></p>
  17. <dividdivid="CnLei_1"style="CSS display:none;">CnLei_1</div>
  18. <dividdivid="CnLei_2"style="visibility:hidden;">CnLei_2</div>
  19. <scripttypescripttype="text/javascript">
  20. varw3c=(document.getElementById)?true:false;
  21. varagt=navigator.userAgent.toLowerCase();
  22. varie=((agt.indexOf("msie")!=-1)
  23. &&(agt.indexOf("opera")==-1)&&(agt.indexOf("omniweb")==-1));
  24. varie5=(w3c&&ie)?true:false;
  25. varns6=(w3c&&(navigator.appName=="Netscape"))?true:false;
  26. function$(o){
  27. returndocument.getElementById(o)?document.getElementById(o):o;
  28. }
  29. functionGetXYWH(o){
  30. varo=$(o);
  31. varnLt=0;
  32. varnTop=0;
  33. varoffsetParent=o;
  34. while(offsetParent!=null&&offsetParent!=document.body){
  35. nLt+=offsetParent.offsetLeft;
  36. nTop+=offsetParent.offsetTop;
  37. if(!ns6){
  38. parseInt(offsetParent.currentStyle.borderLeftWidth)>0?
  39. nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
  40. parseInt(offsetParent.currentStyle.borderTopWidth)>0?
  41. nTop+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
  42. }
  43. offsetParentoffsetParent=offsetParent.offsetParent;
  44. }
  45. return{X:nLt,Y:nTop,W:o.offsetWidth,H:o.offsetHeight};
  46. }
  47. </script>
  48. </body>
  49. </html>
原文地址:https://www.cnblogs.com/huzefeng/p/2534264.html