首页 > 开发 > CSS > 正文

display:none和visibility:hidden的差别比较与演示代码

2024-07-11 08:29:11
字体:
来源:转载
供稿:网友

前言:
在使用css隐藏栏位或物件的时候,
常常会使用到display:none和visibility:hidden这两个属性,
但却很容易分不清楚这两个的差别,
或是乾脆同时使用两种属性,来确保物件一定被隐藏,
其实我们可以很简单的来区分两者的差别。

AD:
你知道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元素(对象)仅仅是在视觉上看不见(完全透明),而它所占据的空间位置仍然存在,也即是说它仍具有高度、宽度等属性值。
具体区别请看演示代码吧:

复制代码
代码如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml"lang="gb2312">
<head>
<head>
<title>实例演示:CSS display:none和visible:hidden的区别</title>
<metahttp-equivmetahttp-equiv="content-type"content="text/html;charset=gb2312"/>
<metahttp-equivmetahttp-equiv="content-type"content="text/html;charset=gb2312"/>
<metanamemetaname="author"content="枫岩,CnLei.y.l@gmail.com">
<metanamemetaname="copyright"content="http://www.cnlei.com"/>
</head>
<body>
<p><ahrefahref="javascript:alert($('CnLei_1').innerHTML+'的宽度:/n'
+GetXYWH($('CnLei_1')).W);">点击这里CSS display:none;</a></p>
<p><ahrefahref="javascript:alert($('CnLei_2').innerHTML+'的宽度:/n'
+GetXYWH($('CnLei_2')).W);">点击这里visibility:hidden;</a></p>
<dividdivid="CnLei_1"style="CSS display:none;">CnLei_1</div>
<dividdivid="CnLei_2"style="visibility:hidden;">CnLei_2</div>
<scripttypescripttype="text/javascript">
varw3c=(document.getElementById)?true:false;
varagt=navigator.userAgent.toLowerCase();
varie=((agt.indexOf("msie")!=-1)
&&(agt.indexOf("opera")==-1)&&(agt.indexOf("omniweb")==-1));
varie5=(w3c&&ie)?true:false;
varns6=(w3c&&(navigator.appName=="Netscape"))?true:false;
function$(o){
returndocument.getElementById(o)?document.getElementById(o):o;
}
functionGetXYWH(o){
varo=$(o);
varnLt=0;
varnTop=0;
varoffsetParent=o;
while(offsetParent!=null&&offsetParent!=document.body){
nLt+=offsetParent.offsetLeft;
nTop+=offsetParent.offsetTop;
if(!ns6){
parseInt(offsetParent.currentStyle.borderLeftWidth)>0?
nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
parseInt(offsetParent.currentStyle.borderTopWidth)>0?
nTop+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
}
offsetParentoffsetParent=offsetParent.offsetParent;
}
return{X:nLt,Y:nTop,W:o.offsetWidth,H:o.offsetHeight};
}
</script>
</body>
</html>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表