ドキュメント

Tutorials:Mouse Position

From jQuery JavaScript Library

Jump to: navigation, search

Some quick examples of finding the position of the mouse on a page.

Original: http://docs.jquery.com/Tutorials:Mouse_Position
Author: Patrick Hall

Similar Tutorials: EventsAttributes

Contents

How do I find the mouse position?

The details of finding the mouse position with Javascript across browsers are a bit hairy; for the gruesome details check out ppk's cross-browser comparison.

jQuery makes detecting the mouse position easy. You just have to learn how to read the .pageX and .pageY attributes off of events, and they'll tell you where the mouse is (in pixels) just at the moment the event takes place.

Tracking mouse position

As you can see if you move your mouse, the values are constantly read and updated as the mouse moves:

0, 0

Here's the source for that example:


<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 
})
</script>
<body>
<h2 id="status">
0, 0
</h2>
</body>
</html>

Where did they click that div?

.pageX and .pageY can be read off of any event, not just .mousemove().

For example, perhaps you want to know exactly where a user clicked inside a particular div:

Here's an example where we listen for a click event inside a particular div called #special.


pageX, pageY

Click me anywhere!

Here's how that works:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})
</script>
<body>

<h2 id="status2">
0, 0
</h2>
<div style="width: 100px; height: 100px; background:#ccc;" id="special">
Click me anywhere!
</div>
</body>
</html>


(Note that the pixel values give are relative to the entire document. If you want to calculate the position within a particular element, or within the viewport, you can look at offsetY and offsetX, and do a bit of arithmetic to find the relative value.

Here is an example of finding the position within the particular element rather than the page:

   $("#special").click(function(e){

	var x = e.pageX - this.offsetLeft;
	var y = e.pageY - this.offsetTop;

      $('#status2').html(x +', '+ y);
   });

Plugins that refer to mouse position

You can poke around in the source code for these plugins to see how it's used.


thanks to nlogax, Getty, John, and other nice folks in the irc channel for helping with this topic! ☺