javascript getBoundingClientRect() 來獲取頁面元素的位置的代碼[修正版]第1/2頁
更新時(shí)間:2009年05月22日 00:00:59 作者:
該方法已經(jīng)不再是IE Only了,F(xiàn)F3.0+和Opera9.5+已經(jīng)支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對(duì)位置。
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.
還是實(shí)際解釋下,該方法獲得頁面中某個(gè)元素的左,上,右和下分別相對(duì)瀏覽器視窗的位置。也不好理解,下面用圖說明下。
該方法已經(jīng)不再是IE Only了,F(xiàn)F3.0+和Opera9.5+已經(jīng)支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對(duì)位置。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
有了這個(gè)方法,獲取頁面元素的位置就簡單多了,
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.
還是實(shí)際解釋下,該方法獲得頁面中某個(gè)元素的左,上,右和下分別相對(duì)瀏覽器視窗的位置。也不好理解,下面用圖說明下。
該方法已經(jīng)不再是IE Only了,F(xiàn)F3.0+和Opera9.5+已經(jīng)支持了該方法,可以說在獲得頁面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必須通過循環(huán)來獲得元素在頁面中的絕對(duì)位置。
下面的代碼舉了個(gè)簡單的例子,可以滾動(dòng)滾動(dòng)條之后點(diǎn)紅色區(qū)域看各個(gè)值的變化。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
有了這個(gè)方法,獲取頁面元素的位置就簡單多了,
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;
相關(guān)文章
JavaScript中使用stopPropagation函數(shù)停止事件傳播例子
這篇文章主要介紹了JavaScript中使用stopPropagation函數(shù)停止事件傳播例子,即阻止事件冒泡的一個(gè)方法,需要的朋友可以參考下2014-08-08javascript將數(shù)組插入到另一個(gè)數(shù)組中的代碼
下面的代碼主要功能就是將數(shù)組arr2插入到數(shù)組arr1的index位置,需要的朋友可以參考下2013-01-01