分享

使用getBoundingClientRect需要注意的地方

 woshishenxiande 2010-12-01

使用getBoundingClientRect需要注意的地方

Javascript 2010-07-13 18:37:07 阅读42 评论0   字号: 订阅

这次试验同样的也说明IETester与系统自带的IE浏览器的差异

页面代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www./1999/xhtml">
<head>
<title>getBoundingClientRect测试例子</title>
<meta name="generator" content="editplus" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type='text/css'>
body {margin:0; padding:0;}
#demo {border:1px solid #f00; width:300px;margin:30px 10px 0 10px; padding:10px;}
</style>
</head>

<body>
<div id='demo'>xxxx</div>

<script type="text/javascript">
function $(id) {
   return typeof id === 'string' ? document.getElementById(id) : id;
}

function getStyle(el) {
   return document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(el, '') : el.currentStyle
}

function getOffset(el) {
   var _t = 0, _l = 0;

   while (el.offsetParent) {
    _t += el.offsetTop;
    _l += el.offsetLeft;
    el = el.offsetParent;
   }
   return [_t, _l];
}

alert( $('demo').getBoundingClientRect().left + "---" + getOffset($("demo"))[1] );
</script>

</body>
</html>

getBoundingClientRect是DOM元素到浏览器可视范围的距离(不包含文档卷起的部分),firefox3+、chrome2+、opera9.63+都支持这个属性。

上面的代码可存为本地,然后在几个浏览器里运行得到的结果如下:

IE(系统自带的浏览器):12---10

非IE(FF、Opera、Chrome):10---10

所以这里需要注意的问题有两个:

1、要加上文档卷起的部分(scorll的值)

2、IE盒模型2px的差异

可是很奇怪的事情是,如果使用IETester去浏览、测试这个例子,全部都为10-10   奇怪,表现与系统自带的IE还不一样...

获取DOM元素的左顶点距离网页左顶点的位置方法就变成下面的了:

function getXY(el) {
   var rect = el.getBoundingClientRect(),
        scrollTop = Math.max(el.ownerDocument.documentElement.scrollTop,el.ownerDocument.body.scrollTop),
    scrollLeft = Math.max(el.ownerDocument.documentElement.scrollLeft, el.ownerDocument.body.scrollLeft),
    isIE = window.ActiveXObject ? 2 : 0,
    _t = 0,
    _l = 0;
  
   _l = rect.left - isIE + scrollLeft;
   _t = rect.top - isIE + scrollTop;

   return [_t, _l];
}

不过在IETester中测试将会变成8了.........

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多