getClientRects獲取元素占據頁面的所有矩形區域
描述
獲取元素占據頁面的所有矩形區域。語法 var rectCollection = object.getClientRects();值
getClientRects 返回一個TextRectangle集合,就是TextRectangleList對象。TextRectangle對象包含了, top left bottom right width height 六個屬性TextRectangle對于文本對象,W3C提供了一個 TextRectangle 對象,這個對象是對文本區域的一個解釋。這里的文本區域只針對inline 元素,比如:a, span, em這類標簽元素。瀏覽器差異getClientRects() 最先由MS IE提出,后被W3C引入并制訂了標準。目前主流瀏覽器都支持該標準,而IE只支持TextRectangle的top left bottom right四個屬性。IE下可以通過right-left來計算width、bottom-top來計算height。ie 和非ie瀏覽器在使用getClientRects還是有些差別的,ie獲取TextRectangleList的范圍很大。而非ie獲取的范圍比較小, 只有display:inline的對象才能獲取到TextRectangleList,例如em i span 等標簽。應用場景getClientRects常用于獲取鼠標的位置,如放大鏡效果。微博的用戶信息卡也是通過改方法獲得的。---------------------------------------------------------
getBoundingClientRect獲取元素位置 getBoundingClientRect用于獲得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。getBoundingClientRect是DOM元素到瀏覽器可視范圍的距離(不包含文檔卷起的部分)。該函數返回一個Object對象,該對象有6個屬性:top,lef,right,bottom,width,height;這里的top、left和CSS中的理解很相似,width、height是元素自身的寬高,但是right,bottom和css中的理解有點不一樣。right是指元素右邊界距窗口最左邊的距離,bottom是指元素下邊界距窗口最上面的距離。下面這是MSDN對document.documentElement.getBoundingClientRect的解釋:SyntaxoRect = object.getBoundingClientRect()Return ValueReturns a TextRectangle object. Each rectangle has four integer PRoperties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.RemarksThis 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.getBoundingClientRect()最先是IE的私有屬性,現在已經是一個W3C標準。所以你不用當心瀏覽器兼容問題,不過還是有區別的:IE只返回top,lef,right,bottom四個值,不夠可以通過以下方法來獲取width,height的值:
var ro = object.getBoundingClientRect(); var Width = ro.right - ro.left; var Height = ro.bottom - ro.top;兼容所有瀏覽器寫法: var ro = object.getBoundingClientRect(); var Top = ro.top; var Bottom = ro.bottom; var Left = ro.left; var Right = ro.right; var Width = ro.width||Right - Left; var Height = ro.height||Bottom - Top;有了這個方法,獲取頁面元素的位置就簡單多了: var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft; var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;-------------------------------
getClientRects 和 getBoundingClientRect 的區別返回類型差異:getClientRects 返回一個TextRectangle集合,就是TextRectangleList對象。getBoundingClientRect 返回 一個TextRectangle對象,即使DOM里沒有文本也能返回TextRectangle對象.瀏覽器差異:除了safari,Firefox2.0外所有瀏覽器都支持getClientRects和getBoundingClientRect,firefox 3.1給TextRectangle增加了 width 和 height。ie 和非ie瀏覽器在使用getClientRects還是有些差別的,ie獲取TextRectangleList的范圍很大。而非ie獲取的范圍比較小, 只有display:inline的對象才能獲取到TextRectangleList,例如em i span 等標簽。通過測試,至少Chrome 2+/Safari 4/Firefox3.5/0pera 9.63+已經支持getBoundingClientRect方法。使用場景差異:出于瀏覽器兼容的考慮,現在用得最多的是getBoundingClientRect,經常用來獲取一個element元素的viewport坐標。 網上的例子http://www.360doc.com/content/10/1201/16/3877783_74068281.shtmlhttp://www.thinksaas.cn/group/explore/index.php?app=group&ac=topic&id=19176新聞熱點
疑難解答