How to find out the exact position of the mouse cursor when the user clicks a button in Javascript?
I need to set the top and left px numbers for a div based on this data. How might one go about doing this?
So basically when a user clicks on this element. I have a showcontent
function which shows/hides content. But I need to set the top by finding the position of cursor
function 开发者_如何学运维ShowContent(d) {
document.getElementById(d).style.display = "block";
}
This example is based on the jQuery javascript library.
$("#button").click(function(e){
alert("X is: "+e.pageX+" \n Y is:"+e.pageY);
});
Online demo here: http://jsfiddle.net/pGdbD/1/
Try clicking in different parts of the button
If you don't use jquery or another lib, you need to look at this page http://www.quirksmode.org/js/events_properties.html to handle it cross browser. It involves the following properties: Event.clientX or Event.pageX
Otherwise jquery's event has a pageX and pageY properties.
Most libraries have something to do this for you.
Ext-Core: Event.getPageX() http://dev.sencha.com/deploy/dev/docs/source/EventManager.html#method-Ext.EventObject-getPageX
jquery: http://api.jquery.com/event.pageX/
You can use the event.pageX
and event.pageY
properties of the Event object to find out where the mouse was when the event took place. For example:
document.getElementById('yourDiv').addEventListener('click', function(event) {
console.log('X: ' + event.pageX + ' Y: ' + event.pageY);
});
Obviously your actual code would be more complex, using attachEvent
for IE, for instance, but this should show you how it's done.
Edit As Juan quite rightly reminds me, pageX/Y
are not set in Internet Explorer. The following is adapted from the jQuery source code, and works round this problem:
function(event) {
var x, y;
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
x = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
y = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
} else {
x = event.pageX;
y = event.pageY;
}
console.log('X: ' + x + ' Y: ' + y);
}
精彩评论