I have a mousedown
event handler on an img
element:
$('#some_image').bind({
mousedown: function(e) {
var img = e.target;
var relpos = ???;
}
})
How can I get the location of the mousedown
relative to img
? Relative, that is, to any one of img
's corners, whichever is easiest.
FWIW, I'm using jQuery.
(Sorry for the dumb question. I imagine the answer must be trivial, but I can't find it, and it's driving me insane...)
EDIT: OK, here's the answer:
$('#some_image').bind({
mousedown: function(e) {
var offset = $(this).offset();
var relpos = [e.pageX - offset.left, e.pageY - offset.top];
// etc.
}
})
Actually, I found that for what I'm doing it's better to subtract Math.round(offset.left)
and Math.round(offset.top)
rather than the raw offsets, since the latter are not always integers (go figure).
BTW, at least according to Firebug, the event's offsetX
and offsetY
are undefined, and layerX
and layerY
are not even listed among its members.
I have a mousedown
event handler on an img
element:
$('#some_image').bind({
mousedown: function(e) {
var img = e.target;
var relpos = ???;
}
})
How can I get the location of the mousedown
relative to img
? Relative, that is, to any one of img
's corners, whichever is easiest.
FWIW, I'm using jQuery.
(Sorry for the dumb question. I imagine the answer must be trivial, but I can't find it, and it's driving me insane...)
EDIT: OK, here's the answer:
$('#some_image').bind({
mousedown: function(e) {
var offset = $(this).offset();
var relpos = [e.pageX - offset.left, e.pageY - offset.top];
// etc.
}
})
Actually, I found that for what I'm doing it's better to subtract Math.round(offset.left)
and Math.round(offset.top)
rather than the raw offsets, since the latter are not always integers (go figure).
BTW, at least according to Firebug, the event's offsetX
and offsetY
are undefined, and layerX
and layerY
are not even listed among its members.
3 Answers
Reset to default 4I got the answer from this post jQuery get mouse position within an element
$("#something").click(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
});
I guess you can use layerX and layerY.
$('#some_image').bind({
mousedown: function(e) {
var img = e.target;
console.log(e.layerX+","+ e.layerY);
}
});
jQuery's event object has pageX and pageY properties which they returns the position of the mouse pointer, relative to the left edge of the document.
So, simply you need to get that positions on click event and pare with target element's position.
Official jQuery documentation have nice examples about Mouse position tracking.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745399510a4626035.html
评论列表(0条)