javascript getBoundingClientRect() 來獲取頁面元素的位置的代碼[修正版]第1/2頁
更新時間:2009年05月22日 00:00:59 作者:
該方法已經不再是IE Only了,FF3.0+和Opera9.5+已經支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對位置。
document.documentElement.getBoundingClientRect
下面這是MSDN的解釋:
Syntax
oRect = object.getBoundingClientRect()Return Value
Returns a TextRectangle object. Each rectangle has four integer properties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.
Remarks
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.
還是實際解釋下,該方法獲得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。也不好理解,下面用圖說明下。
該方法已經不再是IE Only了,FF3.0+和Opera9.5+已經支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對位置。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
有了這個方法,獲取頁面元素的位置就簡單多了,
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;
下面這是MSDN的解釋:
Syntax
oRect = object.getBoundingClientRect()Return Value
Returns a TextRectangle object. Each rectangle has four integer properties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.
Remarks
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.
還是實際解釋下,該方法獲得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。也不好理解,下面用圖說明下。
該方法已經不再是IE Only了,FF3.0+和Opera9.5+已經支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對位置。
下面的代碼舉了個簡單的例子,可以滾動滾動條之后點紅色區(qū)域看各個值的變化。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
有了這個方法,獲取頁面元素的位置就簡單多了,
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;
相關文章
JavaScript中使用stopPropagation函數停止事件傳播例子
這篇文章主要介紹了JavaScript中使用stopPropagation函數停止事件傳播例子,即阻止事件冒泡的一個方法,需要的朋友可以參考下2014-08-08