getClientRects() 和 getBoundingClientRect() 的用法和区别

getClientRects()

getClientRects()的作用是获取元素占据页面的所有矩形区域:

var rectCollection = object.getClientRects();

getClientRects() 返回一个TextRectangle集合,就是TextRectangleList对象。TextRectangle对象包含了, top, left, bottom, right, width, height六个属性。对于文本对象,W3C提供了一个TextRectangle对象,这个对象是对文本区域的一个解释。这里的文本区域只针对inline 元素,比如:a, span, em这类标签元素。getClientRects()常用于获取鼠标的位置,如放大镜效果。微博的用户信息卡也是通过改方法获得的。

getBoundingClientRect()

getBoundingClientRect()用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。getBoundingClientRect()是DOM元素到浏览器可视范围的距离(不包含页面看不见的部分)。该函数返回一个Object对象,该对象有6个属性:top, left, bottom, right, width, height;这里的top、left和css中的理解很相似,width、height是元素自身的宽高,但是right,bottom和css中的理解有点不一样。right是指元素右边界距窗口最左边的距离,bottom是指元素下边界距窗口最上面的距离。

getClientRects() 和 getBoundingClientRect() 的用法和区别

下面是一个代码例子:

<!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=utf-8" />
<title>Demo</title>
</head>

<body style="width:2000px; height:1000px;">
    <div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px; background:#CC0000; top: 114px;">Demo为了方便就直接用绝对定位的元素</div>
</body>
</html>
<script>
document.getElementById('demo').onclick=function (){
        if (document.documentElement.getBoundingClientRect) { 
            alert("left:"+this.getBoundingClientRect().left)
            alert("top:"+this.getBoundingClientRect().top)
            alert("right:"+this.getBoundingClientRect().right)
            alert("bottom:"+this.getBoundingClientRect().bottom)
            var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
            var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;
            alert("Demo的位置是X:"+X+";Y:"+Y)
        } 
}
</script>

getClientRects 和 getBoundingClientRect 的区别

返回类型差异:

getClientRects 返回一个TextRectangle集合,就是TextRectangleList对象。
getBoundingClientRect 返回 一个TextRectangle对象,即使DOM里没有文本也能返回TextRectangle对象.

阅读余下内容
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号