jQuery IE6下width(),height()获取document的高和宽不精确

jQuery在IE6下width(),height()获取document的高和宽不精确

  最近在学jquery,发现使用$(document).width(),$(document).height()在IE6浏览器下获取到的长度尽然是分辨率的宽和高,而不是document对象的宽,导致lightbox在ie6下出现滚动条。如下图

未显示lightbox前
未显示lightbox前

显示lightbox后
显示lightbox后


  在浏览器地址栏输入JavaScript脚本
javascript:alert($(document).width()+'\n'+document.documentElement.scrollWidth+'\n'+screen.width);void(0)
回车键执行,输出结果如下,得到的结果是screen.width一样,而不是和document.documentElement.scrollWidth一致。

执行JavaScript脚本



  如果去掉xhtml申明,再执行上面的代码,则获取到的都是screen.width。结果如下

去掉xhtml声明后,执行JavaScript脚本


  最后只好自己写代码扩展jquery的功能,获取document的宽了,改jquery的代码有点恐怖。更改过后不再初夏滚动条,注意使用的是扩展的函数,而不是jquery默认的了。
+展开
-JavaScript
var isStrict=document.compatMode == "CSS1Compat";
jQuery.extend({
  w:function(){var w=isStrict?document.documentElement.scrollWidth:document.body.scrollWidth;return Math.max(w,$(window).width());}
 ,h:function(){var h=isStrict?document.documentElement.scrollHeight:document.body.scrollHeight;return Math.max(h,$(window).height());}  
});

修改好后的效果,不出现滚动条



测试代码1,使用jquery默认的width,height函数,出现滚动条
+展开
-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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="../js/jq.js"></script> 
<style type="text/css">
#showboLightBox{position:absolute;left:0px;top:0px;display:none;z-index:100;background:#666;}
</style> 
</head>
<body>
<div id="showboLightBox"></div>
<input type="button" onclick="show()" value="显示lightbox" />
<script type="text/javascript">
function show(){
  var obj=$('#showboLightBox'),doc=$(document);
  obj.width(doc.width());
  obj.height(doc.height());
  obj.show();
  obj.animate({opacity:.4},{duration:200});
}
</script> 
</body>
</html>


测试代码2,使用自己扩展的,未出现滚动条
+展开
-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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="../js/jq.js"></script> 
<style type="text/css">
#showboLightBox{position:absolute;left:0px;top:0px;display:none;z-index:100;background:#666;}
</style> 
</head>
<body>
<div id="showboLightBox"></div>
<input type="button" onclick="show()" value="显示lightbox" />
<script type="text/javascript">
function show(){
  var obj=$('#showboLightBox');
  obj.width($.w());
  obj.height($.h());
  obj.show();
  obj.animate({opacity:.4},{duration:200});
}
</script> 
</body>
</html>

加支付宝好友偷能量挖...


原创文章,转载请注明出处:jQuery IE6下width(),height()获取document的高和宽不精确

评论(0)Web开发网
阅读(188)喜欢(0)JavaScript/Ajax开发技巧