javascript 獲取元素位置的快速方法 getBoundingClientRect()
更新時間:2009年11月26日 00:40:31 作者:
有一種快速獲得網(wǎng)頁元素的位置。那就是使用getBoundingClientRect()方法。
它返回一個對象,其中包含了left、right、top、bottom四個屬性,分別對應(yīng)了該元素的左上角和右下角相對于瀏覽器窗口(viewport)左上角的距離。
所以,網(wǎng)頁元素的相對位置就是
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;
目前,IE、Firefox 3.0+、Opera 9.5+都支持該方法,而Firefox 2.x、Safari、Chrome、Konqueror不支持。
所以,網(wǎng)頁元素的相對位置就是
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;
目前,IE、Firefox 3.0+、Opera 9.5+都支持該方法,而Firefox 2.x、Safari、Chrome、Konqueror不支持。
相關(guān)文章
基于JavaScript實現(xiàn)動態(tài)創(chuàng)建表格和增加表格行數(shù)
這篇文章主要介紹了基于JavaScript實現(xiàn)動態(tài)創(chuàng)建表格和增加表格行數(shù)的相關(guān)資料,需要的朋友可以參考下2015-12-12
innertext , insertadjacentelement , insertadjacenthtml , ins
innertext , insertadjacentelement , insertadjacenthtml , insertadjacenttext 等區(qū)別...2007-06-06
高性能Javascript筆記 數(shù)據(jù)的存儲與訪問性能優(yōu)化
在JavaScript中,數(shù)據(jù)的存儲位置對代碼的整體性能有著重要的影響。有四種數(shù)據(jù)訪問類型:直接量,局部變量,數(shù)組項,對象成員2012-08-08

