JavaScript教程:Table行定位效果(6)

http://www.itjxue.com  2015-08-06 23:10  来源:未知  点击次数: 

【元素位置】

table的样式设置好后,还需要获取原table和原tr的位置参数,为后面的元素定位做准备。
要获取某个元素相对文档的位置,传统的做法是获取对象的offsetLeft/offsetTop,然后不断获取offsetParent的offsetLeft/offsetTop,直到找不到offsetParent为止。
得到的结果就是相对文档的位置了,上面已经介绍过offsetParent,原理应该都明白了吧。

不过这里介绍一个更好的方法,通过getBoundingClientRect方法来获取。
在mozilla是这么说明的:
The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport...
返回一个TextRectangle对象,包含left, top, right和bottom几个只读属性,以px为单位来表示边界框相对视窗左上角的位置。(偶英文烂啊)
注意是相对视窗,不是文档哦,如果要相对文档还必须加上scrollLeft/scrollTop。
通过下面的测试可以看到两个方法返回的结果都是相同的:

<!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">
<body>
<style type="text/css">
.t{line-height:40px;width:200px; border:10px solid; margin-top:900px; margin-left:500px;}
</style>
<div class="t" id="t"></div>
<script>
var o = document.getElementById("t");
var rect = o.getBoundingClientRect();
var iLeft1 = rect.left +  document.documentElement.scrollLeft, iTop1 = rect.top +  document.documentElement.scrollTop;
var iLeft2 = o.offsetLeft, iTop2 = o.offsetTop;
while (o.offsetParent) { o = o.offsetParent; iLeft2 += o.offsetLeft; iTop2 += o.offsetTop; }
alert(iLeft1+"_"+iLeft2)
alert(iTop1+"_"+iTop2)
</script>
</body>
</html>

程序中就是用getBoundingClientRect来获取位置参数:

//用getBoundingClientRect获取原table位置
var top = this._doc.scrollTop, rect = this._oTable.getBoundingClientRect();
this._oTableLeft = rect.left + this._doc.scrollLeft;
this._oTableTop = rect.top + top;
this._oTableBottom = rect.bottom + top;
//获取原tr位置
rect = this._oRow.getBoundingClientRect();
this._oRowTop = rect.top + top;
this._oRowBottom = rect.bottom + top;

显然用getBoundingClientRect更方便快捷。
这个方法虽然是ie的产物,但已经是w3c的标准,而且ff3,Opera和最新版的chrome都已经支持了这个方法,可以放心使用。
这里只是简单介绍,想了解更多可以看w3c的View Module部分。

获取原table和tr的位置后,还需要计算新table的位置。
程序可以自定义新table位于视窗位置的百分比,例如顶部是0,中间是0.5,底部是1,可以在程序初始化时或用SetPos方法来设置。
这里主要获取视窗高度和新table在视窗的top值:

this._viewHeight = document.documentElement.clientHeight;
this._ntViewTop = (this._viewHeight - this._nTableHeight) * this._pos;

定位范围实际上是从视框顶部到视框高度减去新table高度的范围内的,所以计算时要先把视窗高度减去新table的高度。

(责任编辑:IT教学网)

更多

推荐Javascript/Ajax文章