Search

12/04/2007

clientX / clientY / pageX / pageY

對一個 event 而言,我們常會用到的是 event 的(1)距離 document 左邊距離多少 / (2)距離 document 上面距離多少。
W3C Definition

clientX of type long, readonly
The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.
clientY of type long, readonly
The vertical coordinate at which the event occurred relative to the DOM implementation's client area.

MDC Definition
event.clientX: Returns the horizontal coordinate within the application's client area at which the event occurred (as opposed to the coordinates within the page).
event.pageX: Returns the horizontal coordinate of the event relative to whole document.

DOM標準中,未明確定義 clientX 與 clientY 是相對於 canvas 還是 document,Firefox的作法是以 canvas 為準,並且另外定義以 document為準的 pageX 與 pageY。IE的 implement 是以 canvas 為準,所以需要加上捲軸的高度。其他的瀏覽器(Opera Konqueror iCab)


所以
by document: Mozilla Firefox (pageX/pageY),Opera, Konqueror, iCab
by canvas: Mozilla Firefox (clientX/clientY),IE


var ex, ey;
if(e.pageX && e.pageY){ // Mozilla Firefox
ex = e.pageX;
ey = e.pageY;
}
else if(e.clientx && e.clientY){
ex = e.clientx;
ey = e.clientY;
if(isIE){ // add scrollLeft, scrollTop to it.
ex += document.body.scrollLeft;
ey += document.body.scrollTop;
}
}

ref: PPK - JavaScript - Find position

沒有留言: