admin管理员组

文章数量:1323370

When detecting mouse x and y coordinates, is it best to use event.clientX and event.clientY like this:

function show_coords(event){
  var x=event.clientX;
  var y=event.clientY;
  alert("X coords: " + x + ", Y coords: " + y);
}

or use x and y, like this:

function show_coords(event){
  var x=event.x;
  var y=event.y;
  alert("X coords: " + x + ", Y coords: " + y);
}

Is one method better/faster than the other? They seem to work identically to me.

When detecting mouse x and y coordinates, is it best to use event.clientX and event.clientY like this:

function show_coords(event){
  var x=event.clientX;
  var y=event.clientY;
  alert("X coords: " + x + ", Y coords: " + y);
}

or use x and y, like this:

function show_coords(event){
  var x=event.x;
  var y=event.y;
  alert("X coords: " + x + ", Y coords: " + y);
}

Is one method better/faster than the other? They seem to work identically to me.

Share Improve this question asked Feb 2, 2014 at 15:06 JamesJames 1,8874 gold badges22 silver badges28 bronze badges 2
  • 1 clientX is more cross browser, but still not for all browsers (like FireFox). – putvande Commented Feb 2, 2014 at 15:10
  • event.x is specified in the W3C working drafts, but not supported in many browsers? You'd be better off with clientX, or really any of the others, offsetX, pageX etc. clientX is the currently recmended standard. – adeneo Commented Feb 2, 2014 at 15:14
Add a ment  | 

1 Answer 1

Reset to default 4

I guess event.x/y are defined only in IEs. A quote from IE documentation:

"event.clientX: Retrieves the x-coordinate of the mouse cursor relative to the client area of the window, excluding window decorations or scroll bars."

"event.x: Retrieves the x-coordinate of the mouse cursor relative to the parent element."

As putvande stated, clientX maybe not cross-browser either. pageX/Y might be a safer choice.

本文标签: javascripteventclientX and eventclientY vs eventx and eventyStack Overflow