獲取距窗口的y值
function getTop(e){
var offset=e.offsetTop;
if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
return offset;
}
獲取距窗口的x值
function getLeft(e){
var offset=e.offsetLeft;
if(e.offsetParent!=null) offset+=getLeft(e.offsetParen)
return offset;
}
除了上面的函數以外,還有一種快速方法,可以立刻獲得網頁元素的位置。
那就是使用getBoundingClientRect()方法。它返回一個對象,其中包含了left、right、top、bottom四個屬性,分別對應了該元素的左上角和右下角相對于瀏覽器窗口(viewport)左上角的距離。
所以,網頁元素的相對位置就是
var X= this.getBoundingClientRect().left;
var Y =this.getBoundingClientRect().top;
再加上滾動距離,就可以得到絕對位置
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;
posted on 2011-11-28 14:43
robbin163 閱讀(211)
評論(0) 編輯 收藏