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

0

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

具体区别请看演示代码吧:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”gb2312″>
<head>
<head>
<title> 实例演示:CSS中的display:none和visible:hidden的区别 </title>
<meta http-equiv=”content-type” content=”text/html; charset=gb2312″ />
<meta http-equiv=”content-type” content=”text/html; charset=gb2312″ />
<meta name=”author” content=”枫岩,[email protected]”>
<meta name=”copyright” content=”http://www.cnlei.com” />
</head>
<body>
<p><a href=”javascript:alert($(‘CnLei_1’).innerHTML+’的宽度:\n’+GetXYWH($(‘CnLei_1’)).W);”>点击这里 display:none;</a></p>
<p><a href=”javascript:alert($(‘CnLei_2’).innerHTML+’的宽度:\n’+GetXYWH($(‘CnLei_2’)).W);”>点击这里 visibility:hidden;</a></p>
<div id=”CnLei_1″ style=”display:none;”>CnLei_1</div>
<div id=”CnLei_2″ style=”visibility:hidden;”>CnLei_2</div>

<script type=”text/javascript”>
var w3c=(document.getElementById)? true: false;
var agt=navigator.userAgent.toLowerCase();
var ie = ((agt.indexOf(“msie”) != -1) && (agt.indexOf(“opera”) == -1) && (agt.indexOf(“omniweb”) == -1));
var ie5=(w3c && ie)? true : false;
var ns6=(w3c && (navigator.appName==”Netscape”))? true: false;

function $(o){
return document.getElementById(o)?document.getElementById(o):o;
}

function GetXYWH(o){
var o=$(o);
var nLt=0;
var nTop=0;
var offsetParent = 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):””;
}
offsetParent=offsetParent.offsetParent;
}
return {X:nLt,Y:nTop,W:o.offsetWidth,H:o.offsetHeight};
}
</script>
</body>
</html>

发表评论

您的邮箱不会公开,当您的评论有新的回复时,会通过您填写的邮箱向您发送评论内容。 必填字段 *

为何看不到我发布的评论?

正在提交, 请稍候...