=波波日志 > JavaScript/Ajax > jQuery IE6下width(),height()获取document的高和宽不精确=

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>
类别:JavaScript/Ajax 作者:波波 日期:2010-07-23 【评论:0 阅读:】 
 
暂时没有评论!
发表留言
  • *昵称:
  • 头像:
  • 电子邮件: [留下您的邮件,方便管理员回复您。]
  • 个人网站: *验证码:
声明:本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载或引用的作品侵犯了您的权利,请通知我们,我们会及时删除!
Powered by showbo,G51人力资讯网桂ICP备05005887号