代码改变世界

Thin的DateChooser代码学习(getScrollPosition)(原创,转载请声明)

2006-05-27 11:11  BAsil  阅读(1063)  评论(0编辑  收藏  举报

THIN_CS.prototype.getScrollPosition = function(e)
{
var b=e.document.body;
if(e==b)return {left:0,top:0};
with(e.getBoundingClientRect())
{
return {left:b.scrollLeft+left,top:b.scrollTop+top};
}
}


getBoundingClientRect在msdn的解释

Retrieves an object that specifies the bounds of a collection of TextRectangle objects. (返回一个对象包括所有TextRectangle的数组元素)

TextRectangle在msdn的解释

Specifies a rectangle that contains a line of text in either an element or a TextRange object.

来比较看一下getClientRects

Retrieves a collection of rectangles that describes the layout of the contents of an object or range within the client. Each rectangle describes a single line.

返回一个矩形框的数组,每一个数组表示单独一行,这里好像不是很准确,我们来看一段代码


<body>

<P >Four score and seven years ago
<!-- STYLE="position:absolute; width:200px;
height:100px; overflow:scroll"
onclick=alert(this.scrollLeft+","+this.offsetTop+","+this.style.top+","+this.getBoundingClientRect().top)-->
<!--如果用了绝对/相对定位,则getClientRects()的数组元素为1而不是5-->

<B ID=oDiv ><img src="csdn.gif"> our fathers<BR>
brought forth . . . a new nation, conceived in liberty<BR>
and dedicated to the proposition that all men are<BR>
created equal.</B> Now we are engaged in a great civil war . . .
</P>

</body>
<script>
var s=document.getElementById("oDiv").getClientRects();
alert(s.length);
var b="";
for(var i=0;i<5;i++)
b+=s[i].left+",";
alert(b);

</script>

这段代码对B tag应用getClientRects()得到的TextRectangle Collection是5,而按照msdn中"single line"的理解应该是4

不过在thin的getScrollPosition函数中,我们并没有用到getClientRects()

对于getBoundingClientRect(),会返回一个object。

另外getBoundingClientRect()在msdn的remark

This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client's upper-left corner. In Microsoft® Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client.

也就是说返回的坐标是相对于2,2(pixels)也就是document.body的clientTop和clientLeft。

因此计算ScrollPosition我们要算上scrollLeft和scrollTop的值(这个对于计算两个object之间的距离时,必须用到),对于scrollLeft不明白可以查阅相关资料。

附上msdn中的位置表示的图片,对于理解element dimension 和 location十分有帮助









Technorati : DateChooser getBoundingClientRect getClientRects